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 //===----------------------------------------------------------------------===//
37 #include "Interp/Context.h"
38 #include "Interp/Frame.h"
39 #include "Interp/State.h"
40 #include "clang/AST/APValue.h"
41 #include "clang/AST/ASTContext.h"
42 #include "clang/AST/ASTDiagnostic.h"
43 #include "clang/AST/ASTLambda.h"
44 #include "clang/AST/CXXInheritance.h"
45 #include "clang/AST/CharUnits.h"
46 #include "clang/AST/CurrentSourceLocExprScope.h"
47 #include "clang/AST/Expr.h"
48 #include "clang/AST/OSLog.h"
49 #include "clang/AST/OptionalDiagnostic.h"
50 #include "clang/AST/RecordLayout.h"
51 #include "clang/AST/StmtVisitor.h"
52 #include "clang/AST/TypeLoc.h"
53 #include "clang/Basic/Builtins.h"
54 #include "clang/Basic/FixedPoint.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/SmallBitVector.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
61 #define DEBUG_TYPE "exprconstant"
63 using namespace clang;
74 using SourceLocExprScopeGuard =
75 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
77 static QualType getType(APValue::LValueBase B) {
78 if (!B) return QualType();
79 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
80 // FIXME: It's unclear where we're supposed to take the type from, and
81 // this actually matters for arrays of unknown bound. Eg:
83 // extern int arr[]; void f() { extern int arr[3]; };
84 // constexpr int *p = &arr[1]; // valid?
86 // For now, we take the array bound from the most recent declaration.
87 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
88 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
89 QualType T = Redecl->getType();
90 if (!T->isIncompleteArrayType())
96 if (B.is<TypeInfoLValue>())
97 return B.getTypeInfoType();
99 if (B.is<DynamicAllocLValue>())
100 return B.getDynamicAllocType();
102 const Expr *Base = B.get<const Expr*>();
104 // For a materialized temporary, the type of the temporary we materialized
105 // may not be the type of the expression.
106 if (const MaterializeTemporaryExpr *MTE =
107 dyn_cast<MaterializeTemporaryExpr>(Base)) {
108 SmallVector<const Expr *, 2> CommaLHSs;
109 SmallVector<SubobjectAdjustment, 2> Adjustments;
110 const Expr *Temp = MTE->GetTemporaryExpr();
111 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
113 // Keep any cv-qualifiers from the reference if we generated a temporary
114 // for it directly. Otherwise use the type after adjustment.
115 if (!Adjustments.empty())
116 return Inner->getType();
119 return Base->getType();
122 /// Get an LValue path entry, which is known to not be an array index, as a
123 /// field declaration.
124 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
125 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
127 /// Get an LValue path entry, which is known to not be an array index, as a
128 /// base class declaration.
129 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
130 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
132 /// Determine whether this LValue path entry for a base class names a virtual
134 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
135 return E.getAsBaseOrMember().getInt();
138 /// Given an expression, determine the type used to store the result of
139 /// evaluating that expression.
140 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
143 return Ctx.getLValueReferenceType(E->getType());
146 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
147 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
148 const FunctionDecl *Callee = CE->getDirectCallee();
149 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
152 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
153 /// This will look through a single cast.
155 /// Returns null if we couldn't unwrap a function with alloc_size.
156 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
157 if (!E->getType()->isPointerType())
160 E = E->IgnoreParens();
161 // If we're doing a variable assignment from e.g. malloc(N), there will
162 // probably be a cast of some kind. In exotic cases, we might also see a
163 // top-level ExprWithCleanups. Ignore them either way.
164 if (const auto *FE = dyn_cast<FullExpr>(E))
165 E = FE->getSubExpr()->IgnoreParens();
167 if (const auto *Cast = dyn_cast<CastExpr>(E))
168 E = Cast->getSubExpr()->IgnoreParens();
170 if (const auto *CE = dyn_cast<CallExpr>(E))
171 return getAllocSizeAttr(CE) ? CE : nullptr;
175 /// Determines whether or not the given Base contains a call to a function
176 /// with the alloc_size attribute.
177 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
178 const auto *E = Base.dyn_cast<const Expr *>();
179 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194 ArrayRef<APValue::LValuePathEntry> Path,
195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&
200 "Unsized arrays shouldn't appear here");
201 unsigned MostDerivedLength = 0;
202 Type = getType(Base);
204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205 if (Type->isArrayType()) {
206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
208 MostDerivedLength = I + 1;
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
214 assert(I == 0 && "unexpected unsized array designator");
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
222 MostDerivedLength = I + 1;
224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
227 MostDerivedLength = I + 1;
230 // Path[I] describes a base class.
235 return MostDerivedLength;
238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
243 unsigned Invalid : 1;
245 /// Is this a pointer one past the end of an object?
246 unsigned IsOnePastTheEnd : 1;
248 /// Indicator of whether the first entry is an unsized array.
249 unsigned FirstEntryIsAnUnsizedArray : 1;
251 /// Indicator of whether the most-derived object is an array element.
252 unsigned MostDerivedIsArrayElement : 1;
254 /// The length of the path to the most-derived object of which this is a
256 unsigned MostDerivedPathLength : 28;
258 /// The size of the array of which the most-derived object is an element.
259 /// This will always be 0 if the most-derived object is not an array
260 /// element. 0 is not an indicator of whether or not the most-derived object
261 /// is an array, however, because 0-length arrays are allowed.
263 /// If the current array is an unsized array, the value of this is
265 uint64_t MostDerivedArraySize;
267 /// The type of the most derived object referred to by this address.
268 QualType MostDerivedType;
270 typedef APValue::LValuePathEntry PathEntry;
272 /// The entries on the path from the glvalue to the designated subobject.
273 SmallVector<PathEntry, 8> Entries;
275 SubobjectDesignator() : Invalid(true) {}
277 explicit SubobjectDesignator(QualType T)
278 : Invalid(false), IsOnePastTheEnd(false),
279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
283 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
289 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
290 ArrayRef<PathEntry> VEntries = V.getLValuePath();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292 if (V.getLValueBase()) {
293 bool IsArray = false;
294 bool FirstIsUnsizedArray = false;
295 MostDerivedPathLength = findMostDerivedSubobject(
296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
297 MostDerivedType, IsArray, FirstIsUnsizedArray);
298 MostDerivedIsArrayElement = IsArray;
299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305 unsigned NewLength) {
309 assert(Base && "cannot truncate path for null pointer");
310 assert(NewLength <= Entries.size() && "not a truncation");
312 if (NewLength == Entries.size())
314 Entries.resize(NewLength);
316 bool IsArray = false;
317 bool FirstIsUnsizedArray = false;
318 MostDerivedPathLength = findMostDerivedSubobject(
319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320 FirstIsUnsizedArray);
321 MostDerivedIsArrayElement = IsArray;
322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
330 /// Determine whether the most derived subobject is an array without a
332 bool isMostDerivedAnUnsizedArray() const {
333 assert(!Invalid && "Calling this makes no sense on invalid designators");
334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
337 /// Determine what the most derived array's size is. Results in an assertion
338 /// failure if the most derived array lacks a size.
339 uint64_t getMostDerivedArraySize() const {
340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341 return MostDerivedArraySize;
344 /// Determine whether this is a one-past-the-end pointer.
345 bool isOnePastTheEnd() const {
349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
356 /// Get the range of valid index adjustments in the form
357 /// {maximum value that can be subtracted from this pointer,
358 /// maximum value that can be added to this pointer}
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
363 // [expr.add]p4: For the purposes of these operators, a pointer to a
364 // nonarray object behaves the same as a pointer to the first element of
365 // an array of length one with the type of the object as its element type.
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
375 /// Check that this refers to a valid subobject.
376 bool isValidSubobject() const {
379 return !isOnePastTheEnd();
381 /// Check that this refers to a valid subobject, and if not, produce a
382 /// relevant diagnostic and set the designator as invalid.
383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
385 /// Get the type of the designated object.
386 QualType getType(ASTContext &Ctx) const {
387 assert(!Invalid && "invalid designator has no subobject type");
388 return MostDerivedPathLength == Entries.size()
390 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
393 /// Update this designator to refer to the first element within this array.
394 void addArrayUnchecked(const ConstantArrayType *CAT) {
395 Entries.push_back(PathEntry::ArrayIndex(0));
397 // This is a most-derived object.
398 MostDerivedType = CAT->getElementType();
399 MostDerivedIsArrayElement = true;
400 MostDerivedArraySize = CAT->getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
403 /// Update this designator to refer to the first element within the array of
404 /// elements of type T. This is an array of unknown size.
405 void addUnsizedArrayUnchecked(QualType ElemTy) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement = true;
410 // The value in MostDerivedArraySize is undefined in this case. So, set it
411 // to an arbitrary value that's likely to loudly break things if it's
413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
414 MostDerivedPathLength = Entries.size();
416 /// Update this designator to refer to the given base or member of this
418 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
421 // If this isn't a base class, it's a new most-derived object.
422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
424 MostDerivedIsArrayElement = false;
425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
429 /// Update this designator to refer to the given complex component.
430 void addComplexUnchecked(QualType EltTy, bool Imag) {
431 Entries.push_back(PathEntry::ArrayIndex(Imag));
433 // This is technically a most-derived object, though in practice this
434 // is unlikely to matter.
435 MostDerivedType = EltTy;
436 MostDerivedIsArrayElement = true;
437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
443 /// Add N to the address of this subobject.
444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445 if (Invalid || !N) return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
449 // Can't verify -- trust that the user is doing the right thing (or if
450 // not, trust that the caller will catch the bad behavior).
451 // FIXME: Should we reject if this overflows, at least?
452 Entries.back() = PathEntry::ArrayIndex(
453 Entries.back().getAsArrayIndex() + TruncatedN);
457 // [expr.add]p4: For the purposes of these operators, a pointer to a
458 // nonarray object behaves the same as a pointer to the first element of
459 // an array of length one with the type of the object as its element type.
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468 // Calculate the actual index in a wide enough type, so we can include
470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471 (llvm::APInt&)N += ArrayIndex;
472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
473 diagnosePointerArithmetic(Info, E, N);
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&
480 "bounds check succeeded for out-of-bounds index");
483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
485 IsOnePastTheEnd = (ArrayIndex != 0);
489 /// A stack frame in the constexpr call stack.
490 class CallStackFrame : public interp::Frame {
494 /// Parent - The caller of this stack frame.
495 CallStackFrame *Caller;
497 /// Callee - The function which was called.
498 const FunctionDecl *Callee;
500 /// This - The binding for the this pointer in this call, if any.
503 /// Arguments - Parameter bindings for this function call, indexed by
504 /// parameters' function scope indices.
507 /// Source location information about the default argument or default
508 /// initializer expression we're evaluating, if any.
509 CurrentSourceLocExprScope CurSourceLocExprScope;
511 // Note that we intentionally use std::map here so that references to
512 // values are stable.
513 typedef std::pair<const void *, unsigned> MapKeyTy;
514 typedef std::map<MapKeyTy, APValue> MapTy;
515 /// Temporaries - Temporary lvalues materialized within this stack frame.
518 /// CallLoc - The location of the call expression for this call.
519 SourceLocation CallLoc;
521 /// Index - The call index of this call.
524 /// The stack of integers for tracking version numbers for temporaries.
525 SmallVector<unsigned, 2> TempVersionStack = {1};
526 unsigned CurTempVersion = TempVersionStack.back();
528 unsigned getTempVersion() const { return TempVersionStack.back(); }
530 void pushTempVersion() {
531 TempVersionStack.push_back(++CurTempVersion);
534 void popTempVersion() {
535 TempVersionStack.pop_back();
538 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
539 // on the overall stack usage of deeply-recursing constexpr evaluations.
540 // (We should cache this map rather than recomputing it repeatedly.)
541 // But let's try this and see how it goes; we can look into caching the map
542 // as a later change.
544 /// LambdaCaptureFields - Mapping from captured variables/this to
545 /// corresponding data members in the closure class.
546 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
547 FieldDecl *LambdaThisCaptureField;
549 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
550 const FunctionDecl *Callee, const LValue *This,
554 // Return the temporary for Key whose version number is Version.
555 APValue *getTemporary(const void *Key, unsigned Version) {
556 MapKeyTy KV(Key, Version);
557 auto LB = Temporaries.lower_bound(KV);
558 if (LB != Temporaries.end() && LB->first == KV)
560 // Pair (Key,Version) wasn't found in the map. Check that no elements
561 // in the map have 'Key' as their key.
562 assert((LB == Temporaries.end() || LB->first.first != Key) &&
563 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
564 "Element with key 'Key' found in map");
568 // Return the current temporary for Key in the map.
569 APValue *getCurrentTemporary(const void *Key) {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return &std::prev(UB)->second;
576 // Return the version number of the current temporary for Key.
577 unsigned getCurrentTemporaryVersion(const void *Key) const {
578 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
579 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
580 return std::prev(UB)->first.second;
584 /// Allocate storage for an object of type T in this stack frame.
585 /// Populates LV with a handle to the created object. Key identifies
586 /// the temporary within the stack frame, and must not be reused without
587 /// bumping the temporary version number.
588 template<typename KeyT>
589 APValue &createTemporary(const KeyT *Key, QualType T,
590 bool IsLifetimeExtended, LValue &LV);
592 void describe(llvm::raw_ostream &OS) override;
594 Frame *getCaller() const override { return Caller; }
595 SourceLocation getCallLocation() const override { return CallLoc; }
596 const FunctionDecl *getCallee() const override { return Callee; }
598 bool isStdFunction() const {
599 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
600 if (DC->isStdNamespace())
606 /// Temporarily override 'this'.
607 class ThisOverrideRAII {
609 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
610 : Frame(Frame), OldThis(Frame.This) {
612 Frame.This = NewThis;
614 ~ThisOverrideRAII() {
615 Frame.This = OldThis;
618 CallStackFrame &Frame;
619 const LValue *OldThis;
623 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
624 const LValue &This, QualType ThisType);
625 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
626 APValue::LValueBase LVBase, APValue &Value,
630 /// A cleanup, and a flag indicating whether it is lifetime-extended.
632 llvm::PointerIntPair<APValue*, 1, bool> Value;
633 APValue::LValueBase Base;
637 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
638 bool IsLifetimeExtended)
639 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
641 bool isLifetimeExtended() const { return Value.getInt(); }
642 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
643 if (RunDestructors) {
645 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
646 Loc = VD->getLocation();
647 else if (const Expr *E = Base.dyn_cast<const Expr*>())
648 Loc = E->getExprLoc();
649 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
651 *Value.getPointer() = APValue();
655 bool hasSideEffect() {
656 return T.isDestructedType();
660 /// A reference to an object whose construction we are currently evaluating.
661 struct ObjectUnderConstruction {
662 APValue::LValueBase Base;
663 ArrayRef<APValue::LValuePathEntry> Path;
664 friend bool operator==(const ObjectUnderConstruction &LHS,
665 const ObjectUnderConstruction &RHS) {
666 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
668 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
669 return llvm::hash_combine(Obj.Base, Obj.Path);
672 enum class ConstructionPhase {
682 template<> struct DenseMapInfo<ObjectUnderConstruction> {
683 using Base = DenseMapInfo<APValue::LValueBase>;
684 static ObjectUnderConstruction getEmptyKey() {
685 return {Base::getEmptyKey(), {}}; }
686 static ObjectUnderConstruction getTombstoneKey() {
687 return {Base::getTombstoneKey(), {}};
689 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
690 return hash_value(Object);
692 static bool isEqual(const ObjectUnderConstruction &LHS,
693 const ObjectUnderConstruction &RHS) {
700 /// A dynamically-allocated heap object.
702 /// The value of this heap-allocated object.
704 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
705 /// or a CallExpr (the latter is for direct calls to operator new inside
706 /// std::allocator<T>::allocate).
707 const Expr *AllocExpr = nullptr;
715 /// Get the kind of the allocation. This must match between allocation
716 /// and deallocation.
717 Kind getKind() const {
718 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
719 return NE->isArray() ? ArrayNew : New;
720 assert(isa<CallExpr>(AllocExpr));
725 struct DynAllocOrder {
726 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
727 return L.getIndex() < R.getIndex();
731 /// EvalInfo - This is a private struct used by the evaluator to capture
732 /// information about a subexpression as it is folded. It retains information
733 /// about the AST context, but also maintains information about the folded
736 /// If an expression could be evaluated, it is still possible it is not a C
737 /// "integer constant expression" or constant expression. If not, this struct
738 /// captures information about how and why not.
740 /// One bit of information passed *into* the request for constant folding
741 /// indicates whether the subexpression is "evaluated" or not according to C
742 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
743 /// evaluate the expression regardless of what the RHS is, but C only allows
744 /// certain things in certain situations.
745 class EvalInfo : public interp::State {
749 /// EvalStatus - Contains information about the evaluation.
750 Expr::EvalStatus &EvalStatus;
752 /// CurrentCall - The top of the constexpr call stack.
753 CallStackFrame *CurrentCall;
755 /// CallStackDepth - The number of calls in the call stack right now.
756 unsigned CallStackDepth;
758 /// NextCallIndex - The next call index to assign.
759 unsigned NextCallIndex;
761 /// StepsLeft - The remaining number of evaluation steps we're permitted
762 /// to perform. This is essentially a limit for the number of statements
763 /// we will evaluate.
766 /// Force the use of the experimental new constant interpreter, bailing out
767 /// with an error if a feature is not supported.
768 bool ForceNewConstInterp;
770 /// Enable the experimental new constant interpreter.
771 bool EnableNewConstInterp;
773 /// BottomFrame - The frame in which evaluation started. This must be
774 /// initialized after CurrentCall and CallStackDepth.
775 CallStackFrame BottomFrame;
777 /// A stack of values whose lifetimes end at the end of some surrounding
778 /// evaluation frame.
779 llvm::SmallVector<Cleanup, 16> CleanupStack;
781 /// EvaluatingDecl - This is the declaration whose initializer is being
782 /// evaluated, if any.
783 APValue::LValueBase EvaluatingDecl;
785 enum class EvaluatingDeclKind {
787 /// We're evaluating the construction of EvaluatingDecl.
789 /// We're evaluating the destruction of EvaluatingDecl.
792 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
794 /// EvaluatingDeclValue - This is the value being constructed for the
795 /// declaration whose initializer is being evaluated, if any.
796 APValue *EvaluatingDeclValue;
798 /// Set of objects that are currently being constructed.
799 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800 ObjectsUnderConstruction;
802 /// Current heap allocations, along with the location where each was
803 /// allocated. We use std::map here because we need stable addresses
804 /// for the stored APValues.
805 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
807 /// The number of heap allocations performed so far in this evaluation.
808 unsigned NumHeapAllocs = 0;
810 struct EvaluatingConstructorRAII {
812 ObjectUnderConstruction Object;
814 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
816 : EI(EI), Object(Object) {
818 EI.ObjectsUnderConstruction
819 .insert({Object, HasBases ? ConstructionPhase::Bases
820 : ConstructionPhase::AfterBases})
823 void finishedConstructingBases() {
824 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
826 ~EvaluatingConstructorRAII() {
827 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
831 struct EvaluatingDestructorRAII {
833 ObjectUnderConstruction Object;
835 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
836 : EI(EI), Object(Object) {
837 DidInsert = EI.ObjectsUnderConstruction
838 .insert({Object, ConstructionPhase::Destroying})
841 void startedDestroyingBases() {
842 EI.ObjectsUnderConstruction[Object] =
843 ConstructionPhase::DestroyingBases;
845 ~EvaluatingDestructorRAII() {
847 EI.ObjectsUnderConstruction.erase(Object);
852 isEvaluatingCtorDtor(APValue::LValueBase Base,
853 ArrayRef<APValue::LValuePathEntry> Path) {
854 return ObjectsUnderConstruction.lookup({Base, Path});
857 /// If we're currently speculatively evaluating, the outermost call stack
858 /// depth at which we can mutate state, otherwise 0.
859 unsigned SpeculativeEvaluationDepth = 0;
861 /// The current array initialization index, if we're performing array
863 uint64_t ArrayInitIndex = -1;
865 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
866 /// notes attached to it will also be stored, otherwise they will not be.
867 bool HasActiveDiagnostic;
869 /// Have we emitted a diagnostic explaining why we couldn't constant
870 /// fold (not just why it's not strictly a constant expression)?
871 bool HasFoldFailureDiagnostic;
873 /// Whether or not we're in a context where the front end requires a
875 bool InConstantContext;
877 /// Whether we're checking that an expression is a potential constant
878 /// expression. If so, do not fail on constructs that could become constant
879 /// later on (such as a use of an undefined global).
880 bool CheckingPotentialConstantExpression = false;
882 /// Whether we're checking for an expression that has undefined behavior.
883 /// If so, we will produce warnings if we encounter an operation that is
884 /// always undefined.
885 bool CheckingForUndefinedBehavior = false;
887 enum EvaluationMode {
888 /// Evaluate as a constant expression. Stop if we find that the expression
889 /// is not a constant expression.
890 EM_ConstantExpression,
892 /// Evaluate as a constant expression. Stop if we find that the expression
893 /// is not a constant expression. Some expressions can be retried in the
894 /// optimizer if we don't constant fold them here, but in an unevaluated
895 /// context we try to fold them immediately since the optimizer never
896 /// gets a chance to look at it.
897 EM_ConstantExpressionUnevaluated,
899 /// Fold the expression to a constant. Stop if we hit a side-effect that
903 /// Evaluate in any way we know how. Don't worry about side-effects that
904 /// can't be modeled.
905 EM_IgnoreSideEffects,
908 /// Are we checking whether the expression is a potential constant
910 bool checkingPotentialConstantExpression() const override {
911 return CheckingPotentialConstantExpression;
914 /// Are we checking an expression for overflow?
915 // FIXME: We should check for any kind of undefined or suspicious behavior
916 // in such constructs, not just overflow.
917 bool checkingForUndefinedBehavior() const override {
918 return CheckingForUndefinedBehavior;
921 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
922 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
923 CallStackDepth(0), NextCallIndex(1),
924 StepsLeft(getLangOpts().ConstexprStepLimit),
925 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
926 EnableNewConstInterp(ForceNewConstInterp ||
927 getLangOpts().EnableNewConstInterp),
928 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
929 EvaluatingDecl((const ValueDecl *)nullptr),
930 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
931 HasFoldFailureDiagnostic(false), InConstantContext(false),
938 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
939 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
940 EvaluatingDecl = Base;
941 IsEvaluatingDecl = EDK;
942 EvaluatingDeclValue = &Value;
945 bool CheckCallLimit(SourceLocation Loc) {
946 // Don't perform any constexpr calls (other than the call we're checking)
947 // when checking a potential constant expression.
948 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
950 if (NextCallIndex == 0) {
951 // NextCallIndex has wrapped around.
952 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
955 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
957 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
958 << getLangOpts().ConstexprCallDepth;
962 std::pair<CallStackFrame *, unsigned>
963 getCallFrameAndDepth(unsigned CallIndex) {
964 assert(CallIndex && "no call index in getCallFrameAndDepth");
965 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
966 // be null in this loop.
967 unsigned Depth = CallStackDepth;
968 CallStackFrame *Frame = CurrentCall;
969 while (Frame->Index > CallIndex) {
970 Frame = Frame->Caller;
973 if (Frame->Index == CallIndex)
974 return {Frame, Depth};
978 bool nextStep(const Stmt *S) {
980 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
987 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
989 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
990 Optional<DynAlloc*> Result;
991 auto It = HeapAllocs.find(DA);
992 if (It != HeapAllocs.end())
993 Result = &It->second;
997 /// Information about a stack frame for std::allocator<T>::[de]allocate.
998 struct StdAllocatorCaller {
1001 explicit operator bool() const { return FrameIndex != 0; };
1004 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1005 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1006 Call = Call->Caller) {
1007 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1010 const IdentifierInfo *FnII = MD->getIdentifier();
1011 if (!FnII || !FnII->isStr(FnName))
1015 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1019 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1020 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1021 if (CTSD->isInStdNamespace() && ClassII &&
1022 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1023 TAL[0].getKind() == TemplateArgument::Type)
1024 return {Call->Index, TAL[0].getAsType()};
1030 void performLifetimeExtension() {
1031 // Disable the cleanups for lifetime-extended temporaries.
1033 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1034 [](Cleanup &C) { return C.isLifetimeExtended(); }),
1035 CleanupStack.end());
1038 /// Throw away any remaining cleanups at the end of evaluation. If any
1039 /// cleanups would have had a side-effect, note that as an unmodeled
1040 /// side-effect and return false. Otherwise, return true.
1041 bool discardCleanups() {
1042 for (Cleanup &C : CleanupStack)
1043 if (C.hasSideEffect())
1044 if (!noteSideEffect())
1050 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1051 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1053 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1054 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1056 void setFoldFailureDiagnostic(bool Flag) override {
1057 HasFoldFailureDiagnostic = Flag;
1060 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1062 ASTContext &getCtx() const override { return Ctx; }
1064 // If we have a prior diagnostic, it will be noting that the expression
1065 // isn't a constant expression. This diagnostic is more important,
1066 // unless we require this evaluation to produce a constant expression.
1068 // FIXME: We might want to show both diagnostics to the user in
1069 // EM_ConstantFold mode.
1070 bool hasPriorDiagnostic() override {
1071 if (!EvalStatus.Diag->empty()) {
1073 case EM_ConstantFold:
1074 case EM_IgnoreSideEffects:
1075 if (!HasFoldFailureDiagnostic)
1077 // We've already failed to fold something. Keep that diagnostic.
1079 case EM_ConstantExpression:
1080 case EM_ConstantExpressionUnevaluated:
1081 setActiveDiagnostic(false);
1088 unsigned getCallStackDepth() override { return CallStackDepth; }
1091 /// Should we continue evaluation after encountering a side-effect that we
1093 bool keepEvaluatingAfterSideEffect() {
1095 case EM_IgnoreSideEffects:
1098 case EM_ConstantExpression:
1099 case EM_ConstantExpressionUnevaluated:
1100 case EM_ConstantFold:
1101 // By default, assume any side effect might be valid in some other
1102 // evaluation of this expression from a different context.
1103 return checkingPotentialConstantExpression() ||
1104 checkingForUndefinedBehavior();
1106 llvm_unreachable("Missed EvalMode case");
1109 /// Note that we have had a side-effect, and determine whether we should
1110 /// keep evaluating.
1111 bool noteSideEffect() {
1112 EvalStatus.HasSideEffects = true;
1113 return keepEvaluatingAfterSideEffect();
1116 /// Should we continue evaluation after encountering undefined behavior?
1117 bool keepEvaluatingAfterUndefinedBehavior() {
1119 case EM_IgnoreSideEffects:
1120 case EM_ConstantFold:
1123 case EM_ConstantExpression:
1124 case EM_ConstantExpressionUnevaluated:
1125 return checkingForUndefinedBehavior();
1127 llvm_unreachable("Missed EvalMode case");
1130 /// Note that we hit something that was technically undefined behavior, but
1131 /// that we can evaluate past it (such as signed overflow or floating-point
1132 /// division by zero.)
1133 bool noteUndefinedBehavior() override {
1134 EvalStatus.HasUndefinedBehavior = true;
1135 return keepEvaluatingAfterUndefinedBehavior();
1138 /// Should we continue evaluation as much as possible after encountering a
1139 /// construct which can't be reduced to a value?
1140 bool keepEvaluatingAfterFailure() const override {
1145 case EM_ConstantExpression:
1146 case EM_ConstantExpressionUnevaluated:
1147 case EM_ConstantFold:
1148 case EM_IgnoreSideEffects:
1149 return checkingPotentialConstantExpression() ||
1150 checkingForUndefinedBehavior();
1152 llvm_unreachable("Missed EvalMode case");
1155 /// Notes that we failed to evaluate an expression that other expressions
1156 /// directly depend on, and determine if we should keep evaluating. This
1157 /// should only be called if we actually intend to keep evaluating.
1159 /// Call noteSideEffect() instead if we may be able to ignore the value that
1160 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1162 /// (Foo(), 1) // use noteSideEffect
1163 /// (Foo() || true) // use noteSideEffect
1164 /// Foo() + 1 // use noteFailure
1165 LLVM_NODISCARD bool noteFailure() {
1166 // Failure when evaluating some expression often means there is some
1167 // subexpression whose evaluation was skipped. Therefore, (because we
1168 // don't track whether we skipped an expression when unwinding after an
1169 // evaluation failure) every evaluation failure that bubbles up from a
1170 // subexpression implies that a side-effect has potentially happened. We
1171 // skip setting the HasSideEffects flag to true until we decide to
1172 // continue evaluating after that point, which happens here.
1173 bool KeepGoing = keepEvaluatingAfterFailure();
1174 EvalStatus.HasSideEffects |= KeepGoing;
1178 class ArrayInitLoopIndex {
1180 uint64_t OuterIndex;
1183 ArrayInitLoopIndex(EvalInfo &Info)
1184 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1185 Info.ArrayInitIndex = 0;
1187 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1189 operator uint64_t&() { return Info.ArrayInitIndex; }
1193 /// Object used to treat all foldable expressions as constant expressions.
1194 struct FoldConstant {
1197 bool HadNoPriorDiags;
1198 EvalInfo::EvaluationMode OldMode;
1200 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1203 HadNoPriorDiags(Info.EvalStatus.Diag &&
1204 Info.EvalStatus.Diag->empty() &&
1205 !Info.EvalStatus.HasSideEffects),
1206 OldMode(Info.EvalMode) {
1208 Info.EvalMode = EvalInfo::EM_ConstantFold;
1210 void keepDiagnostics() { Enabled = false; }
1212 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1213 !Info.EvalStatus.HasSideEffects)
1214 Info.EvalStatus.Diag->clear();
1215 Info.EvalMode = OldMode;
1219 /// RAII object used to set the current evaluation mode to ignore
1221 struct IgnoreSideEffectsRAII {
1223 EvalInfo::EvaluationMode OldMode;
1224 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1225 : Info(Info), OldMode(Info.EvalMode) {
1226 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1229 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1232 /// RAII object used to optionally suppress diagnostics and side-effects from
1233 /// a speculative evaluation.
1234 class SpeculativeEvaluationRAII {
1235 EvalInfo *Info = nullptr;
1236 Expr::EvalStatus OldStatus;
1237 unsigned OldSpeculativeEvaluationDepth;
1239 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1241 OldStatus = Other.OldStatus;
1242 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1243 Other.Info = nullptr;
1246 void maybeRestoreState() {
1250 Info->EvalStatus = OldStatus;
1251 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1255 SpeculativeEvaluationRAII() = default;
1257 SpeculativeEvaluationRAII(
1258 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1259 : Info(&Info), OldStatus(Info.EvalStatus),
1260 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1261 Info.EvalStatus.Diag = NewDiag;
1262 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1265 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1266 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1267 moveFromAndCancel(std::move(Other));
1270 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1271 maybeRestoreState();
1272 moveFromAndCancel(std::move(Other));
1276 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1279 /// RAII object wrapping a full-expression or block scope, and handling
1280 /// the ending of the lifetime of temporaries created within it.
1281 template<bool IsFullExpression>
1284 unsigned OldStackSize;
1286 ScopeRAII(EvalInfo &Info)
1287 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1288 // Push a new temporary version. This is needed to distinguish between
1289 // temporaries created in different iterations of a loop.
1290 Info.CurrentCall->pushTempVersion();
1292 bool destroy(bool RunDestructors = true) {
1293 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1298 if (OldStackSize != -1U)
1300 // Body moved to a static method to encourage the compiler to inline away
1301 // instances of this class.
1302 Info.CurrentCall->popTempVersion();
1305 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1306 unsigned OldStackSize) {
1307 assert(OldStackSize <= Info.CleanupStack.size() &&
1308 "running cleanups out of order?");
1310 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1311 // for a full-expression scope.
1312 bool Success = true;
1313 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1314 if (!(IsFullExpression &&
1315 Info.CleanupStack[I - 1].isLifetimeExtended())) {
1316 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1323 // Compact lifetime-extended cleanups.
1324 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1325 if (IsFullExpression)
1327 std::remove_if(NewEnd, Info.CleanupStack.end(),
1328 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1329 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1333 typedef ScopeRAII<false> BlockScopeRAII;
1334 typedef ScopeRAII<true> FullExpressionRAII;
1337 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1338 CheckSubobjectKind CSK) {
1341 if (isOnePastTheEnd()) {
1342 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1347 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1348 // must actually be at least one array element; even a VLA cannot have a
1349 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1353 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1355 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1356 // Do not set the designator as invalid: we can represent this situation,
1357 // and correct handling of __builtin_object_size requires us to do so.
1360 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1363 // If we're complaining, we must be able to statically determine the size of
1364 // the most derived array.
1365 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1366 Info.CCEDiag(E, diag::note_constexpr_array_index)
1368 << static_cast<unsigned>(getMostDerivedArraySize());
1370 Info.CCEDiag(E, diag::note_constexpr_array_index)
1371 << N << /*non-array*/ 1;
1375 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1376 const FunctionDecl *Callee, const LValue *This,
1378 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1379 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1380 Info.CurrentCall = this;
1381 ++Info.CallStackDepth;
1384 CallStackFrame::~CallStackFrame() {
1385 assert(Info.CurrentCall == this && "calls retired out of order");
1386 --Info.CallStackDepth;
1387 Info.CurrentCall = Caller;
1390 static bool isRead(AccessKinds AK) {
1391 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1394 static bool isModification(AccessKinds AK) {
1397 case AK_ReadObjectRepresentation:
1399 case AK_DynamicCast:
1409 llvm_unreachable("unknown access kind");
1412 static bool isAnyAccess(AccessKinds AK) {
1413 return isRead(AK) || isModification(AK);
1416 /// Is this an access per the C++ definition?
1417 static bool isFormalAccess(AccessKinds AK) {
1418 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1422 struct ComplexValue {
1427 APSInt IntReal, IntImag;
1428 APFloat FloatReal, FloatImag;
1430 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1432 void makeComplexFloat() { IsInt = false; }
1433 bool isComplexFloat() const { return !IsInt; }
1434 APFloat &getComplexFloatReal() { return FloatReal; }
1435 APFloat &getComplexFloatImag() { return FloatImag; }
1437 void makeComplexInt() { IsInt = true; }
1438 bool isComplexInt() const { return IsInt; }
1439 APSInt &getComplexIntReal() { return IntReal; }
1440 APSInt &getComplexIntImag() { return IntImag; }
1442 void moveInto(APValue &v) const {
1443 if (isComplexFloat())
1444 v = APValue(FloatReal, FloatImag);
1446 v = APValue(IntReal, IntImag);
1448 void setFrom(const APValue &v) {
1449 assert(v.isComplexFloat() || v.isComplexInt());
1450 if (v.isComplexFloat()) {
1452 FloatReal = v.getComplexFloatReal();
1453 FloatImag = v.getComplexFloatImag();
1456 IntReal = v.getComplexIntReal();
1457 IntImag = v.getComplexIntImag();
1463 APValue::LValueBase Base;
1465 SubobjectDesignator Designator;
1467 bool InvalidBase : 1;
1469 const APValue::LValueBase getLValueBase() const { return Base; }
1470 CharUnits &getLValueOffset() { return Offset; }
1471 const CharUnits &getLValueOffset() const { return Offset; }
1472 SubobjectDesignator &getLValueDesignator() { return Designator; }
1473 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1474 bool isNullPointer() const { return IsNullPtr;}
1476 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1477 unsigned getLValueVersion() const { return Base.getVersion(); }
1479 void moveInto(APValue &V) const {
1480 if (Designator.Invalid)
1481 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1483 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1484 V = APValue(Base, Offset, Designator.Entries,
1485 Designator.IsOnePastTheEnd, IsNullPtr);
1488 void setFrom(ASTContext &Ctx, const APValue &V) {
1489 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1490 Base = V.getLValueBase();
1491 Offset = V.getLValueOffset();
1492 InvalidBase = false;
1493 Designator = SubobjectDesignator(Ctx, V);
1494 IsNullPtr = V.isNullPointer();
1497 void set(APValue::LValueBase B, bool BInvalid = false) {
1499 // We only allow a few types of invalid bases. Enforce that here.
1501 const auto *E = B.get<const Expr *>();
1502 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1503 "Unexpected type of invalid base");
1508 Offset = CharUnits::fromQuantity(0);
1509 InvalidBase = BInvalid;
1510 Designator = SubobjectDesignator(getType(B));
1514 void setNull(ASTContext &Ctx, QualType PointerTy) {
1515 Base = (Expr *)nullptr;
1517 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1518 InvalidBase = false;
1519 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1523 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1527 std::string toString(ASTContext &Ctx, QualType T) const {
1529 moveInto(Printable);
1530 return Printable.getAsString(Ctx, T);
1534 // Check that this LValue is not based on a null pointer. If it is, produce
1535 // a diagnostic and mark the designator as invalid.
1536 template <typename GenDiagType>
1537 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1538 if (Designator.Invalid)
1542 Designator.setInvalid();
1549 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1550 CheckSubobjectKind CSK) {
1551 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1552 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1556 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1558 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1559 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1563 // Check this LValue refers to an object. If not, set the designator to be
1564 // invalid and emit a diagnostic.
1565 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1566 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1567 Designator.checkSubobject(Info, E, CSK);
1570 void addDecl(EvalInfo &Info, const Expr *E,
1571 const Decl *D, bool Virtual = false) {
1572 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1573 Designator.addDeclUnchecked(D, Virtual);
1575 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1576 if (!Designator.Entries.empty()) {
1577 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1578 Designator.setInvalid();
1581 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1582 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1583 Designator.FirstEntryIsAnUnsizedArray = true;
1584 Designator.addUnsizedArrayUnchecked(ElemTy);
1587 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1588 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1589 Designator.addArrayUnchecked(CAT);
1591 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1592 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1593 Designator.addComplexUnchecked(EltTy, Imag);
1595 void clearIsNullPointer() {
1598 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1599 const APSInt &Index, CharUnits ElementSize) {
1600 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1601 // but we're not required to diagnose it and it's valid in C++.)
1605 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1606 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1608 uint64_t Offset64 = Offset.getQuantity();
1609 uint64_t ElemSize64 = ElementSize.getQuantity();
1610 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1611 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1613 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1614 Designator.adjustIndex(Info, E, Index);
1615 clearIsNullPointer();
1617 void adjustOffset(CharUnits N) {
1619 if (N.getQuantity())
1620 clearIsNullPointer();
1626 explicit MemberPtr(const ValueDecl *Decl) :
1627 DeclAndIsDerivedMember(Decl, false), Path() {}
1629 /// The member or (direct or indirect) field referred to by this member
1630 /// pointer, or 0 if this is a null member pointer.
1631 const ValueDecl *getDecl() const {
1632 return DeclAndIsDerivedMember.getPointer();
1634 /// Is this actually a member of some type derived from the relevant class?
1635 bool isDerivedMember() const {
1636 return DeclAndIsDerivedMember.getInt();
1638 /// Get the class which the declaration actually lives in.
1639 const CXXRecordDecl *getContainingRecord() const {
1640 return cast<CXXRecordDecl>(
1641 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1644 void moveInto(APValue &V) const {
1645 V = APValue(getDecl(), isDerivedMember(), Path);
1647 void setFrom(const APValue &V) {
1648 assert(V.isMemberPointer());
1649 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1650 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1652 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1653 Path.insert(Path.end(), P.begin(), P.end());
1656 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1657 /// whether the member is a member of some class derived from the class type
1658 /// of the member pointer.
1659 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1660 /// Path - The path of base/derived classes from the member declaration's
1661 /// class (exclusive) to the class type of the member pointer (inclusive).
1662 SmallVector<const CXXRecordDecl*, 4> Path;
1664 /// Perform a cast towards the class of the Decl (either up or down the
1666 bool castBack(const CXXRecordDecl *Class) {
1667 assert(!Path.empty());
1668 const CXXRecordDecl *Expected;
1669 if (Path.size() >= 2)
1670 Expected = Path[Path.size() - 2];
1672 Expected = getContainingRecord();
1673 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1674 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1675 // if B does not contain the original member and is not a base or
1676 // derived class of the class containing the original member, the result
1677 // of the cast is undefined.
1678 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1679 // (D::*). We consider that to be a language defect.
1685 /// Perform a base-to-derived member pointer cast.
1686 bool castToDerived(const CXXRecordDecl *Derived) {
1689 if (!isDerivedMember()) {
1690 Path.push_back(Derived);
1693 if (!castBack(Derived))
1696 DeclAndIsDerivedMember.setInt(false);
1699 /// Perform a derived-to-base member pointer cast.
1700 bool castToBase(const CXXRecordDecl *Base) {
1704 DeclAndIsDerivedMember.setInt(true);
1705 if (isDerivedMember()) {
1706 Path.push_back(Base);
1709 return castBack(Base);
1713 /// Compare two member pointers, which are assumed to be of the same type.
1714 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1715 if (!LHS.getDecl() || !RHS.getDecl())
1716 return !LHS.getDecl() && !RHS.getDecl();
1717 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1719 return LHS.Path == RHS.Path;
1723 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1724 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1725 const LValue &This, const Expr *E,
1726 bool AllowNonLiteralTypes = false);
1727 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1728 bool InvalidBaseOK = false);
1729 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1730 bool InvalidBaseOK = false);
1731 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1733 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1734 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1735 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1737 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1738 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1739 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1741 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1743 /// Evaluate an integer or fixed point expression into an APResult.
1744 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1747 /// Evaluate only a fixed point expression into an APResult.
1748 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1751 //===----------------------------------------------------------------------===//
1753 //===----------------------------------------------------------------------===//
1755 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1756 /// preserving its value (by extending by up to one bit as needed).
1757 static void negateAsSigned(APSInt &Int) {
1758 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1759 Int = Int.extend(Int.getBitWidth() + 1);
1760 Int.setIsSigned(true);
1765 template<typename KeyT>
1766 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1767 bool IsLifetimeExtended, LValue &LV) {
1768 unsigned Version = getTempVersion();
1769 APValue::LValueBase Base(Key, Index, Version);
1771 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1772 assert(Result.isAbsent() && "temporary created multiple times");
1774 // If we're creating a temporary immediately in the operand of a speculative
1775 // evaluation, don't register a cleanup to be run outside the speculative
1776 // evaluation context, since we won't actually be able to initialize this
1778 if (Index <= Info.SpeculativeEvaluationDepth) {
1779 if (T.isDestructedType())
1780 Info.noteSideEffect();
1782 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1787 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1788 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1789 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1793 DynamicAllocLValue DA(NumHeapAllocs++);
1794 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1795 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1796 std::forward_as_tuple(DA), std::tuple<>());
1797 assert(Result.second && "reused a heap alloc index?");
1798 Result.first->second.AllocExpr = E;
1799 return &Result.first->second.Value;
1802 /// Produce a string describing the given constexpr call.
1803 void CallStackFrame::describe(raw_ostream &Out) {
1804 unsigned ArgIndex = 0;
1805 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1806 !isa<CXXConstructorDecl>(Callee) &&
1807 cast<CXXMethodDecl>(Callee)->isInstance();
1810 Out << *Callee << '(';
1812 if (This && IsMemberCall) {
1814 This->moveInto(Val);
1815 Val.printPretty(Out, Info.Ctx,
1816 This->Designator.MostDerivedType);
1817 // FIXME: Add parens around Val if needed.
1818 Out << "->" << *Callee << '(';
1819 IsMemberCall = false;
1822 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1823 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1824 if (ArgIndex > (unsigned)IsMemberCall)
1827 const ParmVarDecl *Param = *I;
1828 const APValue &Arg = Arguments[ArgIndex];
1829 Arg.printPretty(Out, Info.Ctx, Param->getType());
1831 if (ArgIndex == 0 && IsMemberCall)
1832 Out << "->" << *Callee << '(';
1838 /// Evaluate an expression to see if it had side-effects, and discard its
1840 /// \return \c true if the caller should keep evaluating.
1841 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1843 if (!Evaluate(Scratch, Info, E))
1844 // We don't need the value, but we might have skipped a side effect here.
1845 return Info.noteSideEffect();
1849 /// Should this call expression be treated as a string literal?
1850 static bool IsStringLiteralCall(const CallExpr *E) {
1851 unsigned Builtin = E->getBuiltinCallee();
1852 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1853 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1856 static bool IsGlobalLValue(APValue::LValueBase B) {
1857 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1858 // constant expression of pointer type that evaluates to...
1860 // ... a null pointer value, or a prvalue core constant expression of type
1862 if (!B) return true;
1864 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1865 // ... the address of an object with static storage duration,
1866 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1867 return VD->hasGlobalStorage();
1868 // ... the address of a function,
1869 return isa<FunctionDecl>(D);
1872 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1875 const Expr *E = B.get<const Expr*>();
1876 switch (E->getStmtClass()) {
1879 case Expr::CompoundLiteralExprClass: {
1880 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1881 return CLE->isFileScope() && CLE->isLValue();
1883 case Expr::MaterializeTemporaryExprClass:
1884 // A materialized temporary might have been lifetime-extended to static
1885 // storage duration.
1886 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1887 // A string literal has static storage duration.
1888 case Expr::StringLiteralClass:
1889 case Expr::PredefinedExprClass:
1890 case Expr::ObjCStringLiteralClass:
1891 case Expr::ObjCEncodeExprClass:
1892 case Expr::CXXUuidofExprClass:
1894 case Expr::ObjCBoxedExprClass:
1895 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1896 case Expr::CallExprClass:
1897 return IsStringLiteralCall(cast<CallExpr>(E));
1898 // For GCC compatibility, &&label has static storage duration.
1899 case Expr::AddrLabelExprClass:
1901 // A Block literal expression may be used as the initialization value for
1902 // Block variables at global or local static scope.
1903 case Expr::BlockExprClass:
1904 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1905 case Expr::ImplicitValueInitExprClass:
1907 // We can never form an lvalue with an implicit value initialization as its
1908 // base through expression evaluation, so these only appear in one case: the
1909 // implicit variable declaration we invent when checking whether a constexpr
1910 // constructor can produce a constant expression. We must assume that such
1911 // an expression might be a global lvalue.
1916 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1917 return LVal.Base.dyn_cast<const ValueDecl*>();
1920 static bool IsLiteralLValue(const LValue &Value) {
1921 if (Value.getLValueCallIndex())
1923 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1924 return E && !isa<MaterializeTemporaryExpr>(E);
1927 static bool IsWeakLValue(const LValue &Value) {
1928 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1929 return Decl && Decl->isWeak();
1932 static bool isZeroSized(const LValue &Value) {
1933 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1934 if (Decl && isa<VarDecl>(Decl)) {
1935 QualType Ty = Decl->getType();
1936 if (Ty->isArrayType())
1937 return Ty->isIncompleteType() ||
1938 Decl->getASTContext().getTypeSize(Ty) == 0;
1943 static bool HasSameBase(const LValue &A, const LValue &B) {
1944 if (!A.getLValueBase())
1945 return !B.getLValueBase();
1946 if (!B.getLValueBase())
1949 if (A.getLValueBase().getOpaqueValue() !=
1950 B.getLValueBase().getOpaqueValue()) {
1951 const Decl *ADecl = GetLValueBaseDecl(A);
1954 const Decl *BDecl = GetLValueBaseDecl(B);
1955 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1959 return IsGlobalLValue(A.getLValueBase()) ||
1960 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1961 A.getLValueVersion() == B.getLValueVersion());
1964 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1965 assert(Base && "no location for a null lvalue");
1966 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1968 Info.Note(VD->getLocation(), diag::note_declared_at);
1969 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1970 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1971 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1972 // FIXME: Produce a note for dangling pointers too.
1973 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1974 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1975 diag::note_constexpr_dynamic_alloc_here);
1977 // We have no information to show for a typeid(T) object.
1980 enum class CheckEvaluationResultKind {
1985 /// Materialized temporaries that we've already checked to determine if they're
1986 /// initializsed by a constant expression.
1987 using CheckedTemporaries =
1988 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1990 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1991 EvalInfo &Info, SourceLocation DiagLoc,
1992 QualType Type, const APValue &Value,
1993 Expr::ConstExprUsage Usage,
1994 SourceLocation SubobjectLoc,
1995 CheckedTemporaries &CheckedTemps);
1997 /// Check that this reference or pointer core constant expression is a valid
1998 /// value for an address or reference constant expression. Return true if we
1999 /// can fold this expression, whether or not it's a constant expression.
2000 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2001 QualType Type, const LValue &LVal,
2002 Expr::ConstExprUsage Usage,
2003 CheckedTemporaries &CheckedTemps) {
2004 bool IsReferenceType = Type->isReferenceType();
2006 APValue::LValueBase Base = LVal.getLValueBase();
2007 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2009 // Check that the object is a global. Note that the fake 'this' object we
2010 // manufacture when checking potential constant expressions is conservatively
2011 // assumed to be global here.
2012 if (!IsGlobalLValue(Base)) {
2013 if (Info.getLangOpts().CPlusPlus11) {
2014 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2015 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2016 << IsReferenceType << !Designator.Entries.empty()
2018 NoteLValueLocation(Info, Base);
2022 // Don't allow references to temporaries to escape.
2025 assert((Info.checkingPotentialConstantExpression() ||
2026 LVal.getLValueCallIndex() == 0) &&
2027 "have call index for global lvalue");
2029 if (Base.is<DynamicAllocLValue>()) {
2030 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2031 << IsReferenceType << !Designator.Entries.empty();
2032 NoteLValueLocation(Info, Base);
2036 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2037 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2038 // Check if this is a thread-local variable.
2039 if (Var->getTLSKind())
2040 // FIXME: Diagnostic!
2043 // A dllimport variable never acts like a constant.
2044 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2045 // FIXME: Diagnostic!
2048 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2049 // __declspec(dllimport) must be handled very carefully:
2050 // We must never initialize an expression with the thunk in C++.
2051 // Doing otherwise would allow the same id-expression to yield
2052 // different addresses for the same function in different translation
2053 // units. However, this means that we must dynamically initialize the
2054 // expression with the contents of the import address table at runtime.
2056 // The C language has no notion of ODR; furthermore, it has no notion of
2057 // dynamic initialization. This means that we are permitted to
2058 // perform initialization with the address of the thunk.
2059 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2060 FD->hasAttr<DLLImportAttr>())
2061 // FIXME: Diagnostic!
2064 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2065 Base.dyn_cast<const Expr *>())) {
2066 if (CheckedTemps.insert(MTE).second) {
2067 QualType TempType = getType(Base);
2068 if (TempType.isDestructedType()) {
2069 Info.FFDiag(MTE->getExprLoc(),
2070 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2075 APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2076 assert(V && "evasluation result refers to uninitialised temporary");
2077 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2078 Info, MTE->getExprLoc(), TempType, *V,
2079 Usage, SourceLocation(), CheckedTemps))
2084 // Allow address constant expressions to be past-the-end pointers. This is
2085 // an extension: the standard requires them to point to an object.
2086 if (!IsReferenceType)
2089 // A reference constant expression must refer to an object.
2091 // FIXME: diagnostic
2096 // Does this refer one past the end of some object?
2097 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2098 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2099 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2100 << !Designator.Entries.empty() << !!VD << VD;
2101 NoteLValueLocation(Info, Base);
2107 /// Member pointers are constant expressions unless they point to a
2108 /// non-virtual dllimport member function.
2109 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2112 const APValue &Value,
2113 Expr::ConstExprUsage Usage) {
2114 const ValueDecl *Member = Value.getMemberPointerDecl();
2115 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2118 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2119 !FD->hasAttr<DLLImportAttr>();
2122 /// Check that this core constant expression is of literal type, and if not,
2123 /// produce an appropriate diagnostic.
2124 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2125 const LValue *This = nullptr) {
2126 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2129 // C++1y: A constant initializer for an object o [...] may also invoke
2130 // constexpr constructors for o and its subobjects even if those objects
2131 // are of non-literal class types.
2133 // C++11 missed this detail for aggregates, so classes like this:
2134 // struct foo_t { union { int i; volatile int j; } u; };
2135 // are not (obviously) initializable like so:
2136 // __attribute__((__require_constant_initialization__))
2137 // static const foo_t x = {{0}};
2138 // because "i" is a subobject with non-literal initialization (due to the
2139 // volatile member of the union). See:
2140 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2141 // Therefore, we use the C++1y behavior.
2142 if (This && Info.EvaluatingDecl == This->getLValueBase())
2145 // Prvalue constant expressions must be of literal types.
2146 if (Info.getLangOpts().CPlusPlus11)
2147 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2150 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2154 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2155 EvalInfo &Info, SourceLocation DiagLoc,
2156 QualType Type, const APValue &Value,
2157 Expr::ConstExprUsage Usage,
2158 SourceLocation SubobjectLoc,
2159 CheckedTemporaries &CheckedTemps) {
2160 if (!Value.hasValue()) {
2161 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2163 if (SubobjectLoc.isValid())
2164 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2168 // We allow _Atomic(T) to be initialized from anything that T can be
2169 // initialized from.
2170 if (const AtomicType *AT = Type->getAs<AtomicType>())
2171 Type = AT->getValueType();
2173 // Core issue 1454: For a literal constant expression of array or class type,
2174 // each subobject of its value shall have been initialized by a constant
2176 if (Value.isArray()) {
2177 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2178 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2179 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2180 Value.getArrayInitializedElt(I), Usage,
2181 SubobjectLoc, CheckedTemps))
2184 if (!Value.hasArrayFiller())
2186 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2187 Value.getArrayFiller(), Usage, SubobjectLoc,
2190 if (Value.isUnion() && Value.getUnionField()) {
2191 return CheckEvaluationResult(
2192 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2193 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2196 if (Value.isStruct()) {
2197 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2198 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2199 unsigned BaseIndex = 0;
2200 for (const CXXBaseSpecifier &BS : CD->bases()) {
2201 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2202 Value.getStructBase(BaseIndex), Usage,
2203 BS.getBeginLoc(), CheckedTemps))
2208 for (const auto *I : RD->fields()) {
2209 if (I->isUnnamedBitfield())
2212 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2213 Value.getStructField(I->getFieldIndex()),
2214 Usage, I->getLocation(), CheckedTemps))
2219 if (Value.isLValue() &&
2220 CERK == CheckEvaluationResultKind::ConstantExpression) {
2222 LVal.setFrom(Info.Ctx, Value);
2223 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2227 if (Value.isMemberPointer() &&
2228 CERK == CheckEvaluationResultKind::ConstantExpression)
2229 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2231 // Everything else is fine.
2235 /// Check that this core constant expression value is a valid value for a
2236 /// constant expression. If not, report an appropriate diagnostic. Does not
2237 /// check that the expression is of literal type.
2239 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2240 const APValue &Value,
2241 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2242 CheckedTemporaries CheckedTemps;
2243 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2244 Info, DiagLoc, Type, Value, Usage,
2245 SourceLocation(), CheckedTemps);
2248 /// Check that this evaluated value is fully-initialized and can be loaded by
2249 /// an lvalue-to-rvalue conversion.
2250 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2251 QualType Type, const APValue &Value) {
2252 CheckedTemporaries CheckedTemps;
2253 return CheckEvaluationResult(
2254 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2255 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2258 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2259 /// "the allocated storage is deallocated within the evaluation".
2260 static bool CheckMemoryLeaks(EvalInfo &Info) {
2261 if (!Info.HeapAllocs.empty()) {
2262 // We can still fold to a constant despite a compile-time memory leak,
2263 // so long as the heap allocation isn't referenced in the result (we check
2264 // that in CheckConstantExpression).
2265 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2266 diag::note_constexpr_memory_leak)
2267 << unsigned(Info.HeapAllocs.size() - 1);
2272 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2273 // A null base expression indicates a null pointer. These are always
2274 // evaluatable, and they are false unless the offset is zero.
2275 if (!Value.getLValueBase()) {
2276 Result = !Value.getLValueOffset().isZero();
2280 // We have a non-null base. These are generally known to be true, but if it's
2281 // a weak declaration it can be null at runtime.
2283 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2284 return !Decl || !Decl->isWeak();
2287 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2288 switch (Val.getKind()) {
2290 case APValue::Indeterminate:
2293 Result = Val.getInt().getBoolValue();
2295 case APValue::FixedPoint:
2296 Result = Val.getFixedPoint().getBoolValue();
2298 case APValue::Float:
2299 Result = !Val.getFloat().isZero();
2301 case APValue::ComplexInt:
2302 Result = Val.getComplexIntReal().getBoolValue() ||
2303 Val.getComplexIntImag().getBoolValue();
2305 case APValue::ComplexFloat:
2306 Result = !Val.getComplexFloatReal().isZero() ||
2307 !Val.getComplexFloatImag().isZero();
2309 case APValue::LValue:
2310 return EvalPointerValueAsBool(Val, Result);
2311 case APValue::MemberPointer:
2312 Result = Val.getMemberPointerDecl();
2314 case APValue::Vector:
2315 case APValue::Array:
2316 case APValue::Struct:
2317 case APValue::Union:
2318 case APValue::AddrLabelDiff:
2322 llvm_unreachable("unknown APValue kind");
2325 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2327 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2329 if (!Evaluate(Val, Info, E))
2331 return HandleConversionToBool(Val, Result);
2334 template<typename T>
2335 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2336 const T &SrcValue, QualType DestType) {
2337 Info.CCEDiag(E, diag::note_constexpr_overflow)
2338 << SrcValue << DestType;
2339 return Info.noteUndefinedBehavior();
2342 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2343 QualType SrcType, const APFloat &Value,
2344 QualType DestType, APSInt &Result) {
2345 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2346 // Determine whether we are converting to unsigned or signed.
2347 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2349 Result = APSInt(DestWidth, !DestSigned);
2351 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2352 & APFloat::opInvalidOp)
2353 return HandleOverflow(Info, E, Value, DestType);
2357 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2358 QualType SrcType, QualType DestType,
2360 APFloat Value = Result;
2362 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2363 APFloat::rmNearestTiesToEven, &ignored);
2367 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2368 QualType DestType, QualType SrcType,
2369 const APSInt &Value) {
2370 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2371 // Figure out if this is a truncate, extend or noop cast.
2372 // If the input is signed, do a sign extend, noop, or truncate.
2373 APSInt Result = Value.extOrTrunc(DestWidth);
2374 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2375 if (DestType->isBooleanType())
2376 Result = Value.getBoolValue();
2380 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2381 QualType SrcType, const APSInt &Value,
2382 QualType DestType, APFloat &Result) {
2383 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2384 Result.convertFromAPInt(Value, Value.isSigned(),
2385 APFloat::rmNearestTiesToEven);
2389 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2390 APValue &Value, const FieldDecl *FD) {
2391 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2393 if (!Value.isInt()) {
2394 // Trying to store a pointer-cast-to-integer into a bitfield.
2395 // FIXME: In this case, we should provide the diagnostic for casting
2396 // a pointer to an integer.
2397 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2402 APSInt &Int = Value.getInt();
2403 unsigned OldBitWidth = Int.getBitWidth();
2404 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2405 if (NewBitWidth < OldBitWidth)
2406 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2410 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2413 if (!Evaluate(SVal, Info, E))
2416 Res = SVal.getInt();
2419 if (SVal.isFloat()) {
2420 Res = SVal.getFloat().bitcastToAPInt();
2423 if (SVal.isVector()) {
2424 QualType VecTy = E->getType();
2425 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2426 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2427 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2428 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2429 Res = llvm::APInt::getNullValue(VecSize);
2430 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2431 APValue &Elt = SVal.getVectorElt(i);
2432 llvm::APInt EltAsInt;
2434 EltAsInt = Elt.getInt();
2435 } else if (Elt.isFloat()) {
2436 EltAsInt = Elt.getFloat().bitcastToAPInt();
2438 // Don't try to handle vectors of anything other than int or float
2439 // (not sure if it's possible to hit this case).
2440 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2443 unsigned BaseEltSize = EltAsInt.getBitWidth();
2445 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2447 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2451 // Give up if the input isn't an int, float, or vector. For example, we
2452 // reject "(v4i16)(intptr_t)&a".
2453 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2457 /// Perform the given integer operation, which is known to need at most BitWidth
2458 /// bits, and check for overflow in the original type (if that type was not an
2460 template<typename Operation>
2461 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2462 const APSInt &LHS, const APSInt &RHS,
2463 unsigned BitWidth, Operation Op,
2465 if (LHS.isUnsigned()) {
2466 Result = Op(LHS, RHS);
2470 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2471 Result = Value.trunc(LHS.getBitWidth());
2472 if (Result.extend(BitWidth) != Value) {
2473 if (Info.checkingForUndefinedBehavior())
2474 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2475 diag::warn_integer_constant_overflow)
2476 << Result.toString(10) << E->getType();
2478 return HandleOverflow(Info, E, Value, E->getType());
2483 /// Perform the given binary integer operation.
2484 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2485 BinaryOperatorKind Opcode, APSInt RHS,
2492 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2493 std::multiplies<APSInt>(), Result);
2495 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2496 std::plus<APSInt>(), Result);
2498 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2499 std::minus<APSInt>(), Result);
2500 case BO_And: Result = LHS & RHS; return true;
2501 case BO_Xor: Result = LHS ^ RHS; return true;
2502 case BO_Or: Result = LHS | RHS; return true;
2506 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2509 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2510 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2511 // this operation and gives the two's complement result.
2512 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2513 LHS.isSigned() && LHS.isMinSignedValue())
2514 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2518 if (Info.getLangOpts().OpenCL)
2519 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2520 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2521 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2523 else if (RHS.isSigned() && RHS.isNegative()) {
2524 // During constant-folding, a negative shift is an opposite shift. Such
2525 // a shift is not a constant expression.
2526 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2531 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2532 // the shifted type.
2533 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2535 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2536 << RHS << E->getType() << LHS.getBitWidth();
2537 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2538 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2539 // operand, and must not overflow the corresponding unsigned type.
2540 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2541 // E1 x 2^E2 module 2^N.
2542 if (LHS.isNegative())
2543 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2544 else if (LHS.countLeadingZeros() < SA)
2545 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2551 if (Info.getLangOpts().OpenCL)
2552 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2553 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2554 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2556 else if (RHS.isSigned() && RHS.isNegative()) {
2557 // During constant-folding, a negative shift is an opposite shift. Such a
2558 // shift is not a constant expression.
2559 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2564 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2566 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2568 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2569 << RHS << E->getType() << LHS.getBitWidth();
2574 case BO_LT: Result = LHS < RHS; return true;
2575 case BO_GT: Result = LHS > RHS; return true;
2576 case BO_LE: Result = LHS <= RHS; return true;
2577 case BO_GE: Result = LHS >= RHS; return true;
2578 case BO_EQ: Result = LHS == RHS; return true;
2579 case BO_NE: Result = LHS != RHS; return true;
2581 llvm_unreachable("BO_Cmp should be handled elsewhere");
2585 /// Perform the given binary floating-point operation, in-place, on LHS.
2586 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2587 APFloat &LHS, BinaryOperatorKind Opcode,
2588 const APFloat &RHS) {
2594 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2597 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2600 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2604 // If the second operand of / or % is zero the behavior is undefined.
2606 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2607 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2612 // If during the evaluation of an expression, the result is not
2613 // mathematically defined [...], the behavior is undefined.
2614 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2616 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2617 return Info.noteUndefinedBehavior();
2622 /// Cast an lvalue referring to a base subobject to a derived class, by
2623 /// truncating the lvalue's path to the given length.
2624 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2625 const RecordDecl *TruncatedType,
2626 unsigned TruncatedElements) {
2627 SubobjectDesignator &D = Result.Designator;
2629 // Check we actually point to a derived class object.
2630 if (TruncatedElements == D.Entries.size())
2632 assert(TruncatedElements >= D.MostDerivedPathLength &&
2633 "not casting to a derived class");
2634 if (!Result.checkSubobject(Info, E, CSK_Derived))
2637 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2638 const RecordDecl *RD = TruncatedType;
2639 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2640 if (RD->isInvalidDecl()) return false;
2641 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2642 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2643 if (isVirtualBaseClass(D.Entries[I]))
2644 Result.Offset -= Layout.getVBaseClassOffset(Base);
2646 Result.Offset -= Layout.getBaseClassOffset(Base);
2649 D.Entries.resize(TruncatedElements);
2653 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2654 const CXXRecordDecl *Derived,
2655 const CXXRecordDecl *Base,
2656 const ASTRecordLayout *RL = nullptr) {
2658 if (Derived->isInvalidDecl()) return false;
2659 RL = &Info.Ctx.getASTRecordLayout(Derived);
2662 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2663 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2667 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2668 const CXXRecordDecl *DerivedDecl,
2669 const CXXBaseSpecifier *Base) {
2670 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2672 if (!Base->isVirtual())
2673 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2675 SubobjectDesignator &D = Obj.Designator;
2679 // Extract most-derived object and corresponding type.
2680 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2681 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2684 // Find the virtual base class.
2685 if (DerivedDecl->isInvalidDecl()) return false;
2686 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2687 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2688 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2692 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2693 QualType Type, LValue &Result) {
2694 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2695 PathE = E->path_end();
2696 PathI != PathE; ++PathI) {
2697 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2700 Type = (*PathI)->getType();
2705 /// Cast an lvalue referring to a derived class to a known base subobject.
2706 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2707 const CXXRecordDecl *DerivedRD,
2708 const CXXRecordDecl *BaseRD) {
2709 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2710 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2711 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2712 llvm_unreachable("Class must be derived from the passed in base class!");
2714 for (CXXBasePathElement &Elem : Paths.front())
2715 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2720 /// Update LVal to refer to the given field, which must be a member of the type
2721 /// currently described by LVal.
2722 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2723 const FieldDecl *FD,
2724 const ASTRecordLayout *RL = nullptr) {
2726 if (FD->getParent()->isInvalidDecl()) return false;
2727 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2730 unsigned I = FD->getFieldIndex();
2731 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2732 LVal.addDecl(Info, E, FD);
2736 /// Update LVal to refer to the given indirect field.
2737 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2739 const IndirectFieldDecl *IFD) {
2740 for (const auto *C : IFD->chain())
2741 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2746 /// Get the size of the given type in char units.
2747 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2748 QualType Type, CharUnits &Size) {
2749 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2751 if (Type->isVoidType() || Type->isFunctionType()) {
2752 Size = CharUnits::One();
2756 if (Type->isDependentType()) {
2761 if (!Type->isConstantSizeType()) {
2762 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2763 // FIXME: Better diagnostic.
2768 Size = Info.Ctx.getTypeSizeInChars(Type);
2772 /// Update a pointer value to model pointer arithmetic.
2773 /// \param Info - Information about the ongoing evaluation.
2774 /// \param E - The expression being evaluated, for diagnostic purposes.
2775 /// \param LVal - The pointer value to be updated.
2776 /// \param EltTy - The pointee type represented by LVal.
2777 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2778 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2779 LValue &LVal, QualType EltTy,
2780 APSInt Adjustment) {
2781 CharUnits SizeOfPointee;
2782 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2785 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2789 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2790 LValue &LVal, QualType EltTy,
2791 int64_t Adjustment) {
2792 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2793 APSInt::get(Adjustment));
2796 /// Update an lvalue to refer to a component of a complex number.
2797 /// \param Info - Information about the ongoing evaluation.
2798 /// \param LVal - The lvalue to be updated.
2799 /// \param EltTy - The complex number's component type.
2800 /// \param Imag - False for the real component, true for the imaginary.
2801 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2802 LValue &LVal, QualType EltTy,
2805 CharUnits SizeOfComponent;
2806 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2808 LVal.Offset += SizeOfComponent;
2810 LVal.addComplex(Info, E, EltTy, Imag);
2814 /// Try to evaluate the initializer for a variable declaration.
2816 /// \param Info Information about the ongoing evaluation.
2817 /// \param E An expression to be used when printing diagnostics.
2818 /// \param VD The variable whose initializer should be obtained.
2819 /// \param Frame The frame in which the variable was created. Must be null
2820 /// if this variable is not local to the evaluation.
2821 /// \param Result Filled in with a pointer to the value of the variable.
2822 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2823 const VarDecl *VD, CallStackFrame *Frame,
2824 APValue *&Result, const LValue *LVal) {
2826 // If this is a parameter to an active constexpr function call, perform
2827 // argument substitution.
2828 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2829 // Assume arguments of a potential constant expression are unknown
2830 // constant expressions.
2831 if (Info.checkingPotentialConstantExpression())
2833 if (!Frame || !Frame->Arguments) {
2834 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2837 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2841 // If this is a local variable, dig out its value.
2843 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2844 : Frame->getCurrentTemporary(VD);
2846 // Assume variables referenced within a lambda's call operator that were
2847 // not declared within the call operator are captures and during checking
2848 // of a potential constant expression, assume they are unknown constant
2850 assert(isLambdaCallOperator(Frame->Callee) &&
2851 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2852 "missing value for local variable");
2853 if (Info.checkingPotentialConstantExpression())
2855 // FIXME: implement capture evaluation during constant expr evaluation.
2856 Info.FFDiag(E->getBeginLoc(),
2857 diag::note_unimplemented_constexpr_lambda_feature_ast)
2858 << "captures not currently allowed";
2864 // Dig out the initializer, and use the declaration which it's attached to.
2865 const Expr *Init = VD->getAnyInitializer(VD);
2866 if (!Init || Init->isValueDependent()) {
2867 // If we're checking a potential constant expression, the variable could be
2868 // initialized later.
2869 if (!Info.checkingPotentialConstantExpression())
2870 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2874 // If we're currently evaluating the initializer of this declaration, use that
2876 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2877 Result = Info.EvaluatingDeclValue;
2881 // Never evaluate the initializer of a weak variable. We can't be sure that
2882 // this is the definition which will be used.
2884 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2888 // Check that we can fold the initializer. In C++, we will have already done
2889 // this in the cases where it matters for conformance.
2890 SmallVector<PartialDiagnosticAt, 8> Notes;
2891 if (!VD->evaluateValue(Notes)) {
2892 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2893 Notes.size() + 1) << VD;
2894 Info.Note(VD->getLocation(), diag::note_declared_at);
2895 Info.addNotes(Notes);
2897 } else if (!VD->checkInitIsICE()) {
2898 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2899 Notes.size() + 1) << VD;
2900 Info.Note(VD->getLocation(), diag::note_declared_at);
2901 Info.addNotes(Notes);
2904 Result = VD->getEvaluatedValue();
2908 static bool IsConstNonVolatile(QualType T) {
2909 Qualifiers Quals = T.getQualifiers();
2910 return Quals.hasConst() && !Quals.hasVolatile();
2913 /// Get the base index of the given base class within an APValue representing
2914 /// the given derived class.
2915 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2916 const CXXRecordDecl *Base) {
2917 Base = Base->getCanonicalDecl();
2919 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2920 E = Derived->bases_end(); I != E; ++I, ++Index) {
2921 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2925 llvm_unreachable("base class missing from derived class's bases list");
2928 /// Extract the value of a character from a string literal.
2929 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2931 assert(!isa<SourceLocExpr>(Lit) &&
2932 "SourceLocExpr should have already been converted to a StringLiteral");
2934 // FIXME: Support MakeStringConstant
2935 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2937 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2938 assert(Index <= Str.size() && "Index too large");
2939 return APSInt::getUnsigned(Str.c_str()[Index]);
2942 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2943 Lit = PE->getFunctionName();
2944 const StringLiteral *S = cast<StringLiteral>(Lit);
2945 const ConstantArrayType *CAT =
2946 Info.Ctx.getAsConstantArrayType(S->getType());
2947 assert(CAT && "string literal isn't an array");
2948 QualType CharType = CAT->getElementType();
2949 assert(CharType->isIntegerType() && "unexpected character type");
2951 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2952 CharType->isUnsignedIntegerType());
2953 if (Index < S->getLength())
2954 Value = S->getCodeUnit(Index);
2958 // Expand a string literal into an array of characters.
2960 // FIXME: This is inefficient; we should probably introduce something similar
2961 // to the LLVM ConstantDataArray to make this cheaper.
2962 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2964 QualType AllocType = QualType()) {
2965 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2966 AllocType.isNull() ? S->getType() : AllocType);
2967 assert(CAT && "string literal isn't an array");
2968 QualType CharType = CAT->getElementType();
2969 assert(CharType->isIntegerType() && "unexpected character type");
2971 unsigned Elts = CAT->getSize().getZExtValue();
2972 Result = APValue(APValue::UninitArray(),
2973 std::min(S->getLength(), Elts), Elts);
2974 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2975 CharType->isUnsignedIntegerType());
2976 if (Result.hasArrayFiller())
2977 Result.getArrayFiller() = APValue(Value);
2978 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2979 Value = S->getCodeUnit(I);
2980 Result.getArrayInitializedElt(I) = APValue(Value);
2984 // Expand an array so that it has more than Index filled elements.
2985 static void expandArray(APValue &Array, unsigned Index) {
2986 unsigned Size = Array.getArraySize();
2987 assert(Index < Size);
2989 // Always at least double the number of elements for which we store a value.
2990 unsigned OldElts = Array.getArrayInitializedElts();
2991 unsigned NewElts = std::max(Index+1, OldElts * 2);
2992 NewElts = std::min(Size, std::max(NewElts, 8u));
2994 // Copy the data across.
2995 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2996 for (unsigned I = 0; I != OldElts; ++I)
2997 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2998 for (unsigned I = OldElts; I != NewElts; ++I)
2999 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3000 if (NewValue.hasArrayFiller())
3001 NewValue.getArrayFiller() = Array.getArrayFiller();
3002 Array.swap(NewValue);
3005 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3006 /// conversion. If it's of class type, we may assume that the copy operation
3007 /// is trivial. Note that this is never true for a union type with fields
3008 /// (because the copy always "reads" the active member) and always true for
3009 /// a non-class type.
3010 static bool isReadByLvalueToRvalueConversion(QualType T) {
3011 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3012 if (!RD || (RD->isUnion() && !RD->field_empty()))
3017 for (auto *Field : RD->fields())
3018 if (isReadByLvalueToRvalueConversion(Field->getType()))
3021 for (auto &BaseSpec : RD->bases())
3022 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3028 /// Diagnose an attempt to read from any unreadable field within the specified
3029 /// type, which might be a class type.
3030 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3032 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3036 if (!RD->hasMutableFields())
3039 for (auto *Field : RD->fields()) {
3040 // If we're actually going to read this field in some way, then it can't
3041 // be mutable. If we're in a union, then assigning to a mutable field
3042 // (even an empty one) can change the active member, so that's not OK.
3043 // FIXME: Add core issue number for the union case.
3044 if (Field->isMutable() &&
3045 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3046 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3047 Info.Note(Field->getLocation(), diag::note_declared_at);
3051 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3055 for (auto &BaseSpec : RD->bases())
3056 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3059 // All mutable fields were empty, and thus not actually read.
3063 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3064 APValue::LValueBase Base,
3065 bool MutableSubobject = false) {
3066 // A temporary we created.
3067 if (Base.getCallIndex())
3070 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3074 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3076 switch (Info.IsEvaluatingDecl) {
3077 case EvalInfo::EvaluatingDeclKind::None:
3080 case EvalInfo::EvaluatingDeclKind::Ctor:
3081 // The variable whose initializer we're evaluating.
3083 return declaresSameEntity(Evaluating, BaseD);
3085 // A temporary lifetime-extended by the variable whose initializer we're
3087 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3088 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3089 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3092 case EvalInfo::EvaluatingDeclKind::Dtor:
3093 // C++2a [expr.const]p6:
3094 // [during constant destruction] the lifetime of a and its non-mutable
3095 // subobjects (but not its mutable subobjects) [are] considered to start
3098 // FIXME: We can meaningfully extend this to cover non-const objects, but
3099 // we will need special handling: we should be able to access only
3100 // subobjects of such objects that are themselves declared const.
3102 !(BaseD->getType().isConstQualified() ||
3103 BaseD->getType()->isReferenceType()) ||
3106 return declaresSameEntity(Evaluating, BaseD);
3109 llvm_unreachable("unknown evaluating decl kind");
3113 /// A handle to a complete object (an object that is not a subobject of
3114 /// another object).
3115 struct CompleteObject {
3116 /// The identity of the object.
3117 APValue::LValueBase Base;
3118 /// The value of the complete object.
3120 /// The type of the complete object.
3123 CompleteObject() : Value(nullptr) {}
3124 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3125 : Base(Base), Value(Value), Type(Type) {}
3127 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3128 // In C++14 onwards, it is permitted to read a mutable member whose
3129 // lifetime began within the evaluation.
3130 // FIXME: Should we also allow this in C++11?
3131 if (!Info.getLangOpts().CPlusPlus14)
3133 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3136 explicit operator bool() const { return !Type.isNull(); }
3138 } // end anonymous namespace
3140 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3141 bool IsMutable = false) {
3142 // C++ [basic.type.qualifier]p1:
3143 // - A const object is an object of type const T or a non-mutable subobject
3144 // of a const object.
3145 if (ObjType.isConstQualified() && !IsMutable)
3146 SubobjType.addConst();
3147 // - A volatile object is an object of type const T or a subobject of a
3149 if (ObjType.isVolatileQualified())
3150 SubobjType.addVolatile();
3154 /// Find the designated sub-object of an rvalue.
3155 template<typename SubobjectHandler>
3156 typename SubobjectHandler::result_type
3157 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3158 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3160 // A diagnostic will have already been produced.
3161 return handler.failed();
3162 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3163 if (Info.getLangOpts().CPlusPlus11)
3164 Info.FFDiag(E, Sub.isOnePastTheEnd()
3165 ? diag::note_constexpr_access_past_end
3166 : diag::note_constexpr_access_unsized_array)
3167 << handler.AccessKind;
3170 return handler.failed();
3173 APValue *O = Obj.Value;
3174 QualType ObjType = Obj.Type;
3175 const FieldDecl *LastField = nullptr;
3176 const FieldDecl *VolatileField = nullptr;
3178 // Walk the designator's path to find the subobject.
3179 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3180 // Reading an indeterminate value is undefined, but assigning over one is OK.
3181 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3182 (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
3183 handler.AccessKind != AK_Assign &&
3184 handler.AccessKind != AK_ReadObjectRepresentation)) {
3185 if (!Info.checkingPotentialConstantExpression())
3186 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3187 << handler.AccessKind << O->isIndeterminate();
3188 return handler.failed();
3191 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3192 // const and volatile semantics are not applied on an object under
3193 // {con,de}struction.
3194 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3195 ObjType->isRecordType() &&
3196 Info.isEvaluatingCtorDtor(
3197 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3198 Sub.Entries.begin() + I)) !=
3199 ConstructionPhase::None) {
3200 ObjType = Info.Ctx.getCanonicalType(ObjType);
3201 ObjType.removeLocalConst();
3202 ObjType.removeLocalVolatile();
3205 // If this is our last pass, check that the final object type is OK.
3206 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3207 // Accesses to volatile objects are prohibited.
3208 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3209 if (Info.getLangOpts().CPlusPlus) {
3212 const NamedDecl *Decl = nullptr;
3213 if (VolatileField) {
3215 Loc = VolatileField->getLocation();
3216 Decl = VolatileField;
3217 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3219 Loc = VD->getLocation();
3223 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3224 Loc = E->getExprLoc();
3226 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3227 << handler.AccessKind << DiagKind << Decl;
3228 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3230 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3232 return handler.failed();
3235 // If we are reading an object of class type, there may still be more
3236 // things we need to check: if there are any mutable subobjects, we
3237 // cannot perform this read. (This only happens when performing a trivial
3238 // copy or assignment.)
3239 if (ObjType->isRecordType() &&
3240 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3241 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3242 return handler.failed();
3246 if (!handler.found(*O, ObjType))
3249 // If we modified a bit-field, truncate it to the right width.
3250 if (isModification(handler.AccessKind) &&
3251 LastField && LastField->isBitField() &&
3252 !truncateBitfieldValue(Info, E, *O, LastField))
3258 LastField = nullptr;
3259 if (ObjType->isArrayType()) {
3260 // Next subobject is an array element.
3261 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3262 assert(CAT && "vla in literal type?");
3263 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3264 if (CAT->getSize().ule(Index)) {
3265 // Note, it should not be possible to form a pointer with a valid
3266 // designator which points more than one past the end of the array.
3267 if (Info.getLangOpts().CPlusPlus11)
3268 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3269 << handler.AccessKind;
3272 return handler.failed();
3275 ObjType = CAT->getElementType();
3277 if (O->getArrayInitializedElts() > Index)
3278 O = &O->getArrayInitializedElt(Index);
3279 else if (!isRead(handler.AccessKind)) {
3280 expandArray(*O, Index);
3281 O = &O->getArrayInitializedElt(Index);
3283 O = &O->getArrayFiller();
3284 } else if (ObjType->isAnyComplexType()) {
3285 // Next subobject is a complex number.
3286 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3288 if (Info.getLangOpts().CPlusPlus11)
3289 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3290 << handler.AccessKind;
3293 return handler.failed();
3296 ObjType = getSubobjectType(
3297 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3299 assert(I == N - 1 && "extracting subobject of scalar?");
3300 if (O->isComplexInt()) {
3301 return handler.found(Index ? O->getComplexIntImag()
3302 : O->getComplexIntReal(), ObjType);
3304 assert(O->isComplexFloat());
3305 return handler.found(Index ? O->getComplexFloatImag()
3306 : O->getComplexFloatReal(), ObjType);
3308 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3309 if (Field->isMutable() &&
3310 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3311 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3312 << handler.AccessKind << Field;
3313 Info.Note(Field->getLocation(), diag::note_declared_at);
3314 return handler.failed();
3317 // Next subobject is a class, struct or union field.
3318 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3319 if (RD->isUnion()) {
3320 const FieldDecl *UnionField = O->getUnionField();
3322 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3323 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3324 // Placement new onto an inactive union member makes it active.
3325 O->setUnion(Field, APValue());
3327 // FIXME: If O->getUnionValue() is absent, report that there's no
3328 // active union member rather than reporting the prior active union
3329 // member. We'll need to fix nullptr_t to not use APValue() as its
3330 // representation first.
3331 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3332 << handler.AccessKind << Field << !UnionField << UnionField;
3333 return handler.failed();
3336 O = &O->getUnionValue();
3338 O = &O->getStructField(Field->getFieldIndex());
3340 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3342 if (Field->getType().isVolatileQualified())
3343 VolatileField = Field;
3345 // Next subobject is a base class.
3346 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3347 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3348 O = &O->getStructBase(getBaseIndex(Derived, Base));
3350 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3356 struct ExtractSubobjectHandler {
3360 const AccessKinds AccessKind;
3362 typedef bool result_type;
3363 bool failed() { return false; }
3364 bool found(APValue &Subobj, QualType SubobjType) {
3366 if (AccessKind == AK_ReadObjectRepresentation)
3368 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3370 bool found(APSInt &Value, QualType SubobjType) {
3371 Result = APValue(Value);
3374 bool found(APFloat &Value, QualType SubobjType) {
3375 Result = APValue(Value);
3379 } // end anonymous namespace
3381 /// Extract the designated sub-object of an rvalue.
3382 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3383 const CompleteObject &Obj,
3384 const SubobjectDesignator &Sub, APValue &Result,
3385 AccessKinds AK = AK_Read) {
3386 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3387 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3388 return findSubobject(Info, E, Obj, Sub, Handler);
3392 struct ModifySubobjectHandler {
3397 typedef bool result_type;
3398 static const AccessKinds AccessKind = AK_Assign;
3400 bool checkConst(QualType QT) {
3401 // Assigning to a const object has undefined behavior.
3402 if (QT.isConstQualified()) {
3403 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3409 bool failed() { return false; }
3410 bool found(APValue &Subobj, QualType SubobjType) {
3411 if (!checkConst(SubobjType))
3413 // We've been given ownership of NewVal, so just swap it in.
3414 Subobj.swap(NewVal);
3417 bool found(APSInt &Value, QualType SubobjType) {
3418 if (!checkConst(SubobjType))
3420 if (!NewVal.isInt()) {
3421 // Maybe trying to write a cast pointer value into a complex?
3425 Value = NewVal.getInt();
3428 bool found(APFloat &Value, QualType SubobjType) {
3429 if (!checkConst(SubobjType))
3431 Value = NewVal.getFloat();
3435 } // end anonymous namespace
3437 const AccessKinds ModifySubobjectHandler::AccessKind;
3439 /// Update the designated sub-object of an rvalue to the given value.
3440 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3441 const CompleteObject &Obj,
3442 const SubobjectDesignator &Sub,
3444 ModifySubobjectHandler Handler = { Info, NewVal, E };
3445 return findSubobject(Info, E, Obj, Sub, Handler);
3448 /// Find the position where two subobject designators diverge, or equivalently
3449 /// the length of the common initial subsequence.
3450 static unsigned FindDesignatorMismatch(QualType ObjType,
3451 const SubobjectDesignator &A,
3452 const SubobjectDesignator &B,
3453 bool &WasArrayIndex) {
3454 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3455 for (/**/; I != N; ++I) {
3456 if (!ObjType.isNull() &&
3457 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3458 // Next subobject is an array element.
3459 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3460 WasArrayIndex = true;
3463 if (ObjType->isAnyComplexType())
3464 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3466 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3468 if (A.Entries[I].getAsBaseOrMember() !=
3469 B.Entries[I].getAsBaseOrMember()) {
3470 WasArrayIndex = false;
3473 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3474 // Next subobject is a field.
3475 ObjType = FD->getType();
3477 // Next subobject is a base class.
3478 ObjType = QualType();
3481 WasArrayIndex = false;
3485 /// Determine whether the given subobject designators refer to elements of the
3486 /// same array object.
3487 static bool AreElementsOfSameArray(QualType ObjType,
3488 const SubobjectDesignator &A,
3489 const SubobjectDesignator &B) {
3490 if (A.Entries.size() != B.Entries.size())
3493 bool IsArray = A.MostDerivedIsArrayElement;
3494 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3495 // A is a subobject of the array element.
3498 // If A (and B) designates an array element, the last entry will be the array
3499 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3500 // of length 1' case, and the entire path must match.
3502 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3503 return CommonLength >= A.Entries.size() - IsArray;
3506 /// Find the complete object to which an LValue refers.
3507 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3508 AccessKinds AK, const LValue &LVal,
3509 QualType LValType) {
3510 if (LVal.InvalidBase) {
3512 return CompleteObject();
3516 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3517 return CompleteObject();
3520 CallStackFrame *Frame = nullptr;
3522 if (LVal.getLValueCallIndex()) {
3523 std::tie(Frame, Depth) =
3524 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3526 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3527 << AK << LVal.Base.is<const ValueDecl*>();
3528 NoteLValueLocation(Info, LVal.Base);
3529 return CompleteObject();
3533 bool IsAccess = isAnyAccess(AK);
3535 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3536 // is not a constant expression (even if the object is non-volatile). We also
3537 // apply this rule to C++98, in order to conform to the expected 'volatile'
3539 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3540 if (Info.getLangOpts().CPlusPlus)
3541 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3545 return CompleteObject();
3548 // Compute value storage location and type of base object.
3549 APValue *BaseVal = nullptr;
3550 QualType BaseType = getType(LVal.Base);
3552 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3553 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3554 // In C++11, constexpr, non-volatile variables initialized with constant
3555 // expressions are constant expressions too. Inside constexpr functions,
3556 // parameters are constant expressions even if they're non-const.
3557 // In C++1y, objects local to a constant expression (those with a Frame) are
3558 // both readable and writable inside constant expressions.
3559 // In C, such things can also be folded, although they are not ICEs.
3560 const VarDecl *VD = dyn_cast<VarDecl>(D);
3562 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3565 if (!VD || VD->isInvalidDecl()) {
3567 return CompleteObject();
3570 // Unless we're looking at a local variable or argument in a constexpr call,
3571 // the variable we're reading must be const.
3573 if (Info.getLangOpts().CPlusPlus14 &&
3574 lifetimeStartedInEvaluation(Info, LVal.Base)) {
3575 // OK, we can read and modify an object if we're in the process of
3576 // evaluating its initializer, because its lifetime began in this
3578 } else if (isModification(AK)) {
3579 // All the remaining cases do not permit modification of the object.
3580 Info.FFDiag(E, diag::note_constexpr_modify_global);
3581 return CompleteObject();
3582 } else if (VD->isConstexpr()) {
3583 // OK, we can read this variable.
3584 } else if (BaseType->isIntegralOrEnumerationType()) {
3585 // In OpenCL if a variable is in constant address space it is a const
3587 if (!(BaseType.isConstQualified() ||
3588 (Info.getLangOpts().OpenCL &&
3589 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3591 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3592 if (Info.getLangOpts().CPlusPlus) {
3593 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3594 Info.Note(VD->getLocation(), diag::note_declared_at);
3598 return CompleteObject();
3600 } else if (!IsAccess) {
3601 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3602 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3603 // We support folding of const floating-point types, in order to make
3604 // static const data members of such types (supported as an extension)
3606 if (Info.getLangOpts().CPlusPlus11) {
3607 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3608 Info.Note(VD->getLocation(), diag::note_declared_at);
3612 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3613 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3614 // Keep evaluating to see what we can do.
3616 // FIXME: Allow folding of values of any literal type in all languages.
3617 if (Info.checkingPotentialConstantExpression() &&
3618 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3619 // The definition of this variable could be constexpr. We can't
3620 // access it right now, but may be able to in future.
3621 } else if (Info.getLangOpts().CPlusPlus11) {
3622 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3623 Info.Note(VD->getLocation(), diag::note_declared_at);
3627 return CompleteObject();
3631 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3632 return CompleteObject();
3633 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3634 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3636 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3637 return CompleteObject();
3639 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3640 LVal.Base.getDynamicAllocType());
3642 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3645 if (const MaterializeTemporaryExpr *MTE =
3646 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3647 assert(MTE->getStorageDuration() == SD_Static &&
3648 "should have a frame for a non-global materialized temporary");
3650 // Per C++1y [expr.const]p2:
3651 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3652 // - a [...] glvalue of integral or enumeration type that refers to
3653 // a non-volatile const object [...]
3655 // - a [...] glvalue of literal type that refers to a non-volatile
3656 // object whose lifetime began within the evaluation of e.
3658 // C++11 misses the 'began within the evaluation of e' check and
3659 // instead allows all temporaries, including things like:
3662 // constexpr int k = r;
3663 // Therefore we use the C++14 rules in C++11 too.
3665 // Note that temporaries whose lifetimes began while evaluating a
3666 // variable's constructor are not usable while evaluating the
3667 // corresponding destructor, not even if they're of const-qualified
3669 if (!(BaseType.isConstQualified() &&
3670 BaseType->isIntegralOrEnumerationType()) &&
3671 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3673 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3674 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3675 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3676 return CompleteObject();
3679 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3680 assert(BaseVal && "got reference to unevaluated temporary");
3683 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3686 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3688 << Val.getAsString(Info.Ctx,
3689 Info.Ctx.getLValueReferenceType(LValType));
3690 NoteLValueLocation(Info, LVal.Base);
3691 return CompleteObject();
3694 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3695 assert(BaseVal && "missing value for temporary");
3699 // In C++14, we can't safely access any mutable state when we might be
3700 // evaluating after an unmodeled side effect.
3702 // FIXME: Not all local state is mutable. Allow local constant subobjects
3703 // to be read here (but take care with 'mutable' fields).
3704 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3705 Info.EvalStatus.HasSideEffects) ||
3706 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3707 return CompleteObject();
3709 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3712 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3713 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3714 /// glvalue referred to by an entity of reference type.
3716 /// \param Info - Information about the ongoing evaluation.
3717 /// \param Conv - The expression for which we are performing the conversion.
3718 /// Used for diagnostics.
3719 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3720 /// case of a non-class type).
3721 /// \param LVal - The glvalue on which we are attempting to perform this action.
3722 /// \param RVal - The produced value will be placed here.
3723 /// \param WantObjectRepresentation - If true, we're looking for the object
3724 /// representation rather than the value, and in particular,
3725 /// there is no requirement that the result be fully initialized.
3727 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3728 const LValue &LVal, APValue &RVal,
3729 bool WantObjectRepresentation = false) {
3730 if (LVal.Designator.Invalid)
3733 // Check for special cases where there is no existing APValue to look at.
3734 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3737 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3739 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3740 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3741 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3742 // initializer until now for such expressions. Such an expression can't be
3743 // an ICE in C, so this only matters for fold.
3744 if (Type.isVolatileQualified()) {
3749 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3751 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3752 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3753 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3754 // Special-case character extraction so we don't have to construct an
3755 // APValue for the whole string.
3756 assert(LVal.Designator.Entries.size() <= 1 &&
3757 "Can only read characters from string literals");
3758 if (LVal.Designator.Entries.empty()) {
3759 // Fail for now for LValue to RValue conversion of an array.
3760 // (This shouldn't show up in C/C++, but it could be triggered by a
3761 // weird EvaluateAsRValue call from a tool.)
3765 if (LVal.Designator.isOnePastTheEnd()) {
3766 if (Info.getLangOpts().CPlusPlus11)
3767 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3772 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3773 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3778 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3779 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3782 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3783 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3784 QualType LValType, APValue &Val) {
3785 if (LVal.Designator.Invalid)
3788 if (!Info.getLangOpts().CPlusPlus14) {
3793 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3794 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3798 struct CompoundAssignSubobjectHandler {
3801 QualType PromotedLHSType;
3802 BinaryOperatorKind Opcode;
3805 static const AccessKinds AccessKind = AK_Assign;
3807 typedef bool result_type;
3809 bool checkConst(QualType QT) {
3810 // Assigning to a const object has undefined behavior.
3811 if (QT.isConstQualified()) {
3812 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3818 bool failed() { return false; }
3819 bool found(APValue &Subobj, QualType SubobjType) {
3820 switch (Subobj.getKind()) {
3822 return found(Subobj.getInt(), SubobjType);
3823 case APValue::Float:
3824 return found(Subobj.getFloat(), SubobjType);
3825 case APValue::ComplexInt:
3826 case APValue::ComplexFloat:
3827 // FIXME: Implement complex compound assignment.
3830 case APValue::LValue:
3831 return foundPointer(Subobj, SubobjType);
3833 // FIXME: can this happen?
3838 bool found(APSInt &Value, QualType SubobjType) {
3839 if (!checkConst(SubobjType))
3842 if (!SubobjType->isIntegerType()) {
3843 // We don't support compound assignment on integer-cast-to-pointer
3851 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3852 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3854 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3856 } else if (RHS.isFloat()) {
3857 APFloat FValue(0.0);
3858 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3860 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3861 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3868 bool found(APFloat &Value, QualType SubobjType) {
3869 return checkConst(SubobjType) &&
3870 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3872 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3873 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3875 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3876 if (!checkConst(SubobjType))
3879 QualType PointeeType;
3880 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3881 PointeeType = PT->getPointeeType();
3883 if (PointeeType.isNull() || !RHS.isInt() ||
3884 (Opcode != BO_Add && Opcode != BO_Sub)) {
3889 APSInt Offset = RHS.getInt();
3890 if (Opcode == BO_Sub)
3891 negateAsSigned(Offset);
3894 LVal.setFrom(Info.Ctx, Subobj);
3895 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3897 LVal.moveInto(Subobj);
3901 } // end anonymous namespace
3903 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3905 /// Perform a compound assignment of LVal <op>= RVal.
3906 static bool handleCompoundAssignment(
3907 EvalInfo &Info, const Expr *E,
3908 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3909 BinaryOperatorKind Opcode, const APValue &RVal) {
3910 if (LVal.Designator.Invalid)
3913 if (!Info.getLangOpts().CPlusPlus14) {
3918 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3919 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3921 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3925 struct IncDecSubobjectHandler {
3927 const UnaryOperator *E;
3928 AccessKinds AccessKind;
3931 typedef bool result_type;
3933 bool checkConst(QualType QT) {
3934 // Assigning to a const object has undefined behavior.
3935 if (QT.isConstQualified()) {
3936 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3942 bool failed() { return false; }
3943 bool found(APValue &Subobj, QualType SubobjType) {
3944 // Stash the old value. Also clear Old, so we don't clobber it later
3945 // if we're post-incrementing a complex.
3951 switch (Subobj.getKind()) {
3953 return found(Subobj.getInt(), SubobjType);
3954 case APValue::Float:
3955 return found(Subobj.getFloat(), SubobjType);
3956 case APValue::ComplexInt:
3957 return found(Subobj.getComplexIntReal(),
3958 SubobjType->castAs<ComplexType>()->getElementType()
3959 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3960 case APValue::ComplexFloat:
3961 return found(Subobj.getComplexFloatReal(),
3962 SubobjType->castAs<ComplexType>()->getElementType()
3963 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3964 case APValue::LValue:
3965 return foundPointer(Subobj, SubobjType);
3967 // FIXME: can this happen?
3972 bool found(APSInt &Value, QualType SubobjType) {
3973 if (!checkConst(SubobjType))
3976 if (!SubobjType->isIntegerType()) {
3977 // We don't support increment / decrement on integer-cast-to-pointer
3983 if (Old) *Old = APValue(Value);
3985 // bool arithmetic promotes to int, and the conversion back to bool
3986 // doesn't reduce mod 2^n, so special-case it.
3987 if (SubobjType->isBooleanType()) {
3988 if (AccessKind == AK_Increment)
3995 bool WasNegative = Value.isNegative();
3996 if (AccessKind == AK_Increment) {
3999 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4000 APSInt ActualValue(Value, /*IsUnsigned*/true);
4001 return HandleOverflow(Info, E, ActualValue, SubobjType);
4006 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4007 unsigned BitWidth = Value.getBitWidth();
4008 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4009 ActualValue.setBit(BitWidth);
4010 return HandleOverflow(Info, E, ActualValue, SubobjType);
4015 bool found(APFloat &Value, QualType SubobjType) {
4016 if (!checkConst(SubobjType))
4019 if (Old) *Old = APValue(Value);
4021 APFloat One(Value.getSemantics(), 1);
4022 if (AccessKind == AK_Increment)
4023 Value.add(One, APFloat::rmNearestTiesToEven);
4025 Value.subtract(One, APFloat::rmNearestTiesToEven);
4028 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4029 if (!checkConst(SubobjType))
4032 QualType PointeeType;
4033 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4034 PointeeType = PT->getPointeeType();
4041 LVal.setFrom(Info.Ctx, Subobj);
4042 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4043 AccessKind == AK_Increment ? 1 : -1))
4045 LVal.moveInto(Subobj);
4049 } // end anonymous namespace
4051 /// Perform an increment or decrement on LVal.
4052 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4053 QualType LValType, bool IsIncrement, APValue *Old) {
4054 if (LVal.Designator.Invalid)
4057 if (!Info.getLangOpts().CPlusPlus14) {
4062 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4063 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4064 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4065 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4068 /// Build an lvalue for the object argument of a member function call.
4069 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4071 if (Object->getType()->isPointerType() && Object->isRValue())
4072 return EvaluatePointer(Object, This, Info);
4074 if (Object->isGLValue())
4075 return EvaluateLValue(Object, This, Info);
4077 if (Object->getType()->isLiteralType(Info.Ctx))
4078 return EvaluateTemporary(Object, This, Info);
4080 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4084 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4085 /// lvalue referring to the result.
4087 /// \param Info - Information about the ongoing evaluation.
4088 /// \param LV - An lvalue referring to the base of the member pointer.
4089 /// \param RHS - The member pointer expression.
4090 /// \param IncludeMember - Specifies whether the member itself is included in
4091 /// the resulting LValue subobject designator. This is not possible when
4092 /// creating a bound member function.
4093 /// \return The field or method declaration to which the member pointer refers,
4094 /// or 0 if evaluation fails.
4095 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4099 bool IncludeMember = true) {
4101 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4104 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4105 // member value, the behavior is undefined.
4106 if (!MemPtr.getDecl()) {
4107 // FIXME: Specific diagnostic.
4112 if (MemPtr.isDerivedMember()) {
4113 // This is a member of some derived class. Truncate LV appropriately.
4114 // The end of the derived-to-base path for the base object must match the
4115 // derived-to-base path for the member pointer.
4116 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4117 LV.Designator.Entries.size()) {
4121 unsigned PathLengthToMember =
4122 LV.Designator.Entries.size() - MemPtr.Path.size();
4123 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4124 const CXXRecordDecl *LVDecl = getAsBaseClass(
4125 LV.Designator.Entries[PathLengthToMember + I]);
4126 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4127 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4133 // Truncate the lvalue to the appropriate derived class.
4134 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4135 PathLengthToMember))
4137 } else if (!MemPtr.Path.empty()) {
4138 // Extend the LValue path with the member pointer's path.
4139 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4140 MemPtr.Path.size() + IncludeMember);
4142 // Walk down to the appropriate base class.
4143 if (const PointerType *PT = LVType->getAs<PointerType>())
4144 LVType = PT->getPointeeType();
4145 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4146 assert(RD && "member pointer access on non-class-type expression");
4147 // The first class in the path is that of the lvalue.
4148 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4149 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4150 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4154 // Finally cast to the class containing the member.
4155 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4156 MemPtr.getContainingRecord()))
4160 // Add the member. Note that we cannot build bound member functions here.
4161 if (IncludeMember) {
4162 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4163 if (!HandleLValueMember(Info, RHS, LV, FD))
4165 } else if (const IndirectFieldDecl *IFD =
4166 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4167 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4170 llvm_unreachable("can't construct reference to bound member function");
4174 return MemPtr.getDecl();
4177 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4178 const BinaryOperator *BO,
4180 bool IncludeMember = true) {
4181 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4183 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4184 if (Info.noteFailure()) {
4186 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4191 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4192 BO->getRHS(), IncludeMember);
4195 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4196 /// the provided lvalue, which currently refers to the base object.
4197 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4199 SubobjectDesignator &D = Result.Designator;
4200 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4203 QualType TargetQT = E->getType();
4204 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4205 TargetQT = PT->getPointeeType();
4207 // Check this cast lands within the final derived-to-base subobject path.
4208 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4209 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4210 << D.MostDerivedType << TargetQT;
4214 // Check the type of the final cast. We don't need to check the path,
4215 // since a cast can only be formed if the path is unique.
4216 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4217 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4218 const CXXRecordDecl *FinalType;
4219 if (NewEntriesSize == D.MostDerivedPathLength)
4220 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4222 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4223 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4224 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4225 << D.MostDerivedType << TargetQT;
4229 // Truncate the lvalue to the appropriate derived class.
4230 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4233 /// Get the value to use for a default-initialized object of type T.
4234 static APValue getDefaultInitValue(QualType T) {
4235 if (auto *RD = T->getAsCXXRecordDecl()) {
4237 return APValue((const FieldDecl*)nullptr);
4239 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4240 std::distance(RD->field_begin(), RD->field_end()));
4243 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4244 End = RD->bases_end(); I != End; ++I, ++Index)
4245 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4247 for (const auto *I : RD->fields()) {
4248 if (I->isUnnamedBitfield())
4250 Struct.getStructField(I->getFieldIndex()) =
4251 getDefaultInitValue(I->getType());
4257 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4258 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4259 if (Array.hasArrayFiller())
4260 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4264 return APValue::IndeterminateValue();
4268 enum EvalStmtResult {
4269 /// Evaluation failed.
4271 /// Hit a 'return' statement.
4273 /// Evaluation succeeded.
4275 /// Hit a 'continue' statement.
4277 /// Hit a 'break' statement.
4279 /// Still scanning for 'case' or 'default' statement.
4284 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4285 // We don't need to evaluate the initializer for a static local.
4286 if (!VD->hasLocalStorage())
4291 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4293 const Expr *InitE = VD->getInit();
4295 Val = getDefaultInitValue(VD->getType());
4299 if (InitE->isValueDependent())
4302 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4303 // Wipe out any partially-computed value, to allow tracking that this
4304 // evaluation failed.
4312 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4315 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4316 OK &= EvaluateVarDecl(Info, VD);
4318 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4319 for (auto *BD : DD->bindings())
4320 if (auto *VD = BD->getHoldingVar())
4321 OK &= EvaluateDecl(Info, VD);
4327 /// Evaluate a condition (either a variable declaration or an expression).
4328 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4329 const Expr *Cond, bool &Result) {
4330 FullExpressionRAII Scope(Info);
4331 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4333 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4335 return Scope.destroy();
4339 /// A location where the result (returned value) of evaluating a
4340 /// statement should be stored.
4342 /// The APValue that should be filled in with the returned value.
4344 /// The location containing the result, if any (used to support RVO).
4348 struct TempVersionRAII {
4349 CallStackFrame &Frame;
4351 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4352 Frame.pushTempVersion();
4355 ~TempVersionRAII() {
4356 Frame.popTempVersion();
4362 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4364 const SwitchCase *SC = nullptr);
4366 /// Evaluate the body of a loop, and translate the result as appropriate.
4367 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4369 const SwitchCase *Case = nullptr) {
4370 BlockScopeRAII Scope(Info);
4372 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4373 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4378 return ESR_Succeeded;
4381 return ESR_Continue;
4384 case ESR_CaseNotFound:
4387 llvm_unreachable("Invalid EvalStmtResult!");
4390 /// Evaluate a switch statement.
4391 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4392 const SwitchStmt *SS) {
4393 BlockScopeRAII Scope(Info);
4395 // Evaluate the switch condition.
4398 if (const Stmt *Init = SS->getInit()) {
4399 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4400 if (ESR != ESR_Succeeded) {
4401 if (ESR != ESR_Failed && !Scope.destroy())
4407 FullExpressionRAII CondScope(Info);
4408 if (SS->getConditionVariable() &&
4409 !EvaluateDecl(Info, SS->getConditionVariable()))
4411 if (!EvaluateInteger(SS->getCond(), Value, Info))
4413 if (!CondScope.destroy())
4417 // Find the switch case corresponding to the value of the condition.
4418 // FIXME: Cache this lookup.
4419 const SwitchCase *Found = nullptr;
4420 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4421 SC = SC->getNextSwitchCase()) {
4422 if (isa<DefaultStmt>(SC)) {
4427 const CaseStmt *CS = cast<CaseStmt>(SC);
4428 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4429 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4431 if (LHS <= Value && Value <= RHS) {
4438 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4440 // Search the switch body for the switch case and evaluate it from there.
4441 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4442 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4447 return ESR_Succeeded;
4453 case ESR_CaseNotFound:
4454 // This can only happen if the switch case is nested within a statement
4455 // expression. We have no intention of supporting that.
4456 Info.FFDiag(Found->getBeginLoc(),
4457 diag::note_constexpr_stmt_expr_unsupported);
4460 llvm_unreachable("Invalid EvalStmtResult!");
4463 // Evaluate a statement.
4464 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4465 const Stmt *S, const SwitchCase *Case) {
4466 if (!Info.nextStep(S))
4469 // If we're hunting down a 'case' or 'default' label, recurse through
4470 // substatements until we hit the label.
4472 switch (S->getStmtClass()) {
4473 case Stmt::CompoundStmtClass:
4474 // FIXME: Precompute which substatement of a compound statement we
4475 // would jump to, and go straight there rather than performing a
4476 // linear scan each time.
4477 case Stmt::LabelStmtClass:
4478 case Stmt::AttributedStmtClass:
4479 case Stmt::DoStmtClass:
4482 case Stmt::CaseStmtClass:
4483 case Stmt::DefaultStmtClass:
4488 case Stmt::IfStmtClass: {
4489 // FIXME: Precompute which side of an 'if' we would jump to, and go
4490 // straight there rather than scanning both sides.
4491 const IfStmt *IS = cast<IfStmt>(S);
4493 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4494 // preceded by our switch label.
4495 BlockScopeRAII Scope(Info);
4497 // Step into the init statement in case it brings an (uninitialized)
4498 // variable into scope.
4499 if (const Stmt *Init = IS->getInit()) {
4500 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4501 if (ESR != ESR_CaseNotFound) {
4502 assert(ESR != ESR_Succeeded);
4507 // Condition variable must be initialized if it exists.
4508 // FIXME: We can skip evaluating the body if there's a condition
4509 // variable, as there can't be any case labels within it.
4510 // (The same is true for 'for' statements.)
4512 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4513 if (ESR == ESR_Failed)
4515 if (ESR != ESR_CaseNotFound)
4516 return Scope.destroy() ? ESR : ESR_Failed;
4518 return ESR_CaseNotFound;
4520 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4521 if (ESR == ESR_Failed)
4523 if (ESR != ESR_CaseNotFound)
4524 return Scope.destroy() ? ESR : ESR_Failed;
4525 return ESR_CaseNotFound;
4528 case Stmt::WhileStmtClass: {
4529 EvalStmtResult ESR =
4530 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4531 if (ESR != ESR_Continue)
4536 case Stmt::ForStmtClass: {
4537 const ForStmt *FS = cast<ForStmt>(S);
4538 BlockScopeRAII Scope(Info);
4540 // Step into the init statement in case it brings an (uninitialized)
4541 // variable into scope.
4542 if (const Stmt *Init = FS->getInit()) {
4543 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4544 if (ESR != ESR_CaseNotFound) {
4545 assert(ESR != ESR_Succeeded);
4550 EvalStmtResult ESR =
4551 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4552 if (ESR != ESR_Continue)
4555 FullExpressionRAII IncScope(Info);
4556 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4562 case Stmt::DeclStmtClass: {
4563 // Start the lifetime of any uninitialized variables we encounter. They
4564 // might be used by the selected branch of the switch.
4565 const DeclStmt *DS = cast<DeclStmt>(S);
4566 for (const auto *D : DS->decls()) {
4567 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4568 if (VD->hasLocalStorage() && !VD->getInit())
4569 if (!EvaluateVarDecl(Info, VD))
4571 // FIXME: If the variable has initialization that can't be jumped
4572 // over, bail out of any immediately-surrounding compound-statement
4573 // too. There can't be any case labels here.
4576 return ESR_CaseNotFound;
4580 return ESR_CaseNotFound;
4584 switch (S->getStmtClass()) {
4586 if (const Expr *E = dyn_cast<Expr>(S)) {
4587 // Don't bother evaluating beyond an expression-statement which couldn't
4589 // FIXME: Do we need the FullExpressionRAII object here?
4590 // VisitExprWithCleanups should create one when necessary.
4591 FullExpressionRAII Scope(Info);
4592 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4594 return ESR_Succeeded;
4597 Info.FFDiag(S->getBeginLoc());
4600 case Stmt::NullStmtClass:
4601 return ESR_Succeeded;
4603 case Stmt::DeclStmtClass: {
4604 const DeclStmt *DS = cast<DeclStmt>(S);
4605 for (const auto *D : DS->decls()) {
4606 // Each declaration initialization is its own full-expression.
4607 FullExpressionRAII Scope(Info);
4608 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4610 if (!Scope.destroy())
4613 return ESR_Succeeded;
4616 case Stmt::ReturnStmtClass: {
4617 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4618 FullExpressionRAII Scope(Info);
4621 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4622 : Evaluate(Result.Value, Info, RetExpr)))
4624 return Scope.destroy() ? ESR_Returned : ESR_Failed;
4627 case Stmt::CompoundStmtClass: {
4628 BlockScopeRAII Scope(Info);
4630 const CompoundStmt *CS = cast<CompoundStmt>(S);
4631 for (const auto *BI : CS->body()) {
4632 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4633 if (ESR == ESR_Succeeded)
4635 else if (ESR != ESR_CaseNotFound) {
4636 if (ESR != ESR_Failed && !Scope.destroy())
4642 return ESR_CaseNotFound;
4643 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4646 case Stmt::IfStmtClass: {
4647 const IfStmt *IS = cast<IfStmt>(S);
4649 // Evaluate the condition, as either a var decl or as an expression.
4650 BlockScopeRAII Scope(Info);
4651 if (const Stmt *Init = IS->getInit()) {
4652 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4653 if (ESR != ESR_Succeeded) {
4654 if (ESR != ESR_Failed && !Scope.destroy())
4660 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4663 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4664 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4665 if (ESR != ESR_Succeeded) {
4666 if (ESR != ESR_Failed && !Scope.destroy())
4671 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4674 case Stmt::WhileStmtClass: {
4675 const WhileStmt *WS = cast<WhileStmt>(S);
4677 BlockScopeRAII Scope(Info);
4679 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4685 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4686 if (ESR != ESR_Continue) {
4687 if (ESR != ESR_Failed && !Scope.destroy())
4691 if (!Scope.destroy())
4694 return ESR_Succeeded;
4697 case Stmt::DoStmtClass: {
4698 const DoStmt *DS = cast<DoStmt>(S);
4701 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4702 if (ESR != ESR_Continue)
4706 FullExpressionRAII CondScope(Info);
4707 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4708 !CondScope.destroy())
4711 return ESR_Succeeded;
4714 case Stmt::ForStmtClass: {
4715 const ForStmt *FS = cast<ForStmt>(S);
4716 BlockScopeRAII ForScope(Info);
4717 if (FS->getInit()) {
4718 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4719 if (ESR != ESR_Succeeded) {
4720 if (ESR != ESR_Failed && !ForScope.destroy())
4726 BlockScopeRAII IterScope(Info);
4727 bool Continue = true;
4728 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4729 FS->getCond(), Continue))
4734 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4735 if (ESR != ESR_Continue) {
4736 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4742 FullExpressionRAII IncScope(Info);
4743 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4747 if (!IterScope.destroy())
4750 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4753 case Stmt::CXXForRangeStmtClass: {
4754 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4755 BlockScopeRAII Scope(Info);
4757 // Evaluate the init-statement if present.
4758 if (FS->getInit()) {
4759 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4760 if (ESR != ESR_Succeeded) {
4761 if (ESR != ESR_Failed && !Scope.destroy())
4767 // Initialize the __range variable.
4768 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4769 if (ESR != ESR_Succeeded) {
4770 if (ESR != ESR_Failed && !Scope.destroy())
4775 // Create the __begin and __end iterators.
4776 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4777 if (ESR != ESR_Succeeded) {
4778 if (ESR != ESR_Failed && !Scope.destroy())
4782 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4783 if (ESR != ESR_Succeeded) {
4784 if (ESR != ESR_Failed && !Scope.destroy())
4790 // Condition: __begin != __end.
4792 bool Continue = true;
4793 FullExpressionRAII CondExpr(Info);
4794 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4800 // User's variable declaration, initialized by *__begin.
4801 BlockScopeRAII InnerScope(Info);
4802 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4803 if (ESR != ESR_Succeeded) {
4804 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4810 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4811 if (ESR != ESR_Continue) {
4812 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4817 // Increment: ++__begin
4818 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4821 if (!InnerScope.destroy())
4825 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4828 case Stmt::SwitchStmtClass:
4829 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4831 case Stmt::ContinueStmtClass:
4832 return ESR_Continue;
4834 case Stmt::BreakStmtClass:
4837 case Stmt::LabelStmtClass:
4838 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4840 case Stmt::AttributedStmtClass:
4841 // As a general principle, C++11 attributes can be ignored without
4842 // any semantic impact.
4843 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4846 case Stmt::CaseStmtClass:
4847 case Stmt::DefaultStmtClass:
4848 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4849 case Stmt::CXXTryStmtClass:
4850 // Evaluate try blocks by evaluating all sub statements.
4851 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4855 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4856 /// default constructor. If so, we'll fold it whether or not it's marked as
4857 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4858 /// so we need special handling.
4859 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4860 const CXXConstructorDecl *CD,
4861 bool IsValueInitialization) {
4862 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4865 // Value-initialization does not call a trivial default constructor, so such a
4866 // call is a core constant expression whether or not the constructor is
4868 if (!CD->isConstexpr() && !IsValueInitialization) {
4869 if (Info.getLangOpts().CPlusPlus11) {
4870 // FIXME: If DiagDecl is an implicitly-declared special member function,
4871 // we should be much more explicit about why it's not constexpr.
4872 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4873 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4874 Info.Note(CD->getLocation(), diag::note_declared_at);
4876 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4882 /// CheckConstexprFunction - Check that a function can be called in a constant
4884 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4885 const FunctionDecl *Declaration,
4886 const FunctionDecl *Definition,
4888 // Potential constant expressions can contain calls to declared, but not yet
4889 // defined, constexpr functions.
4890 if (Info.checkingPotentialConstantExpression() && !Definition &&
4891 Declaration->isConstexpr())
4894 // Bail out if the function declaration itself is invalid. We will
4895 // have produced a relevant diagnostic while parsing it, so just
4896 // note the problematic sub-expression.
4897 if (Declaration->isInvalidDecl()) {
4898 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4902 // DR1872: An instantiated virtual constexpr function can't be called in a
4903 // constant expression (prior to C++20). We can still constant-fold such a
4905 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4906 cast<CXXMethodDecl>(Declaration)->isVirtual())
4907 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4909 if (Definition && Definition->isInvalidDecl()) {
4910 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4914 // Can we evaluate this function call?
4915 if (Definition && Definition->isConstexpr() && Body)
4918 if (Info.getLangOpts().CPlusPlus11) {
4919 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4921 // If this function is not constexpr because it is an inherited
4922 // non-constexpr constructor, diagnose that directly.
4923 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4924 if (CD && CD->isInheritingConstructor()) {
4925 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4926 if (!Inherited->isConstexpr())
4927 DiagDecl = CD = Inherited;
4930 // FIXME: If DiagDecl is an implicitly-declared special member function
4931 // or an inheriting constructor, we should be much more explicit about why
4932 // it's not constexpr.
4933 if (CD && CD->isInheritingConstructor())
4934 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4935 << CD->getInheritedConstructor().getConstructor()->getParent();
4937 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4938 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4939 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4941 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4947 struct CheckDynamicTypeHandler {
4948 AccessKinds AccessKind;
4949 typedef bool result_type;
4950 bool failed() { return false; }
4951 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4952 bool found(APSInt &Value, QualType SubobjType) { return true; }
4953 bool found(APFloat &Value, QualType SubobjType) { return true; }
4955 } // end anonymous namespace
4957 /// Check that we can access the notional vptr of an object / determine its
4959 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4960 AccessKinds AK, bool Polymorphic) {
4961 if (This.Designator.Invalid)
4964 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4970 // The object is not usable in constant expressions, so we can't inspect
4971 // its value to see if it's in-lifetime or what the active union members
4972 // are. We can still check for a one-past-the-end lvalue.
4973 if (This.Designator.isOnePastTheEnd() ||
4974 This.Designator.isMostDerivedAnUnsizedArray()) {
4975 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4976 ? diag::note_constexpr_access_past_end
4977 : diag::note_constexpr_access_unsized_array)
4980 } else if (Polymorphic) {
4981 // Conservatively refuse to perform a polymorphic operation if we would
4982 // not be able to read a notional 'vptr' value.
4985 QualType StarThisType =
4986 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4987 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4988 << AK << Val.getAsString(Info.Ctx, StarThisType);
4994 CheckDynamicTypeHandler Handler{AK};
4995 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4998 /// Check that the pointee of the 'this' pointer in a member function call is
4999 /// either within its lifetime or in its period of construction or destruction.
5001 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5003 const CXXMethodDecl *NamedMember) {
5004 return checkDynamicType(
5006 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5009 struct DynamicType {
5010 /// The dynamic class type of the object.
5011 const CXXRecordDecl *Type;
5012 /// The corresponding path length in the lvalue.
5013 unsigned PathLength;
5016 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5017 unsigned PathLength) {
5018 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5019 Designator.Entries.size() && "invalid path length");
5020 return (PathLength == Designator.MostDerivedPathLength)
5021 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5022 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5025 /// Determine the dynamic type of an object.
5026 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5027 LValue &This, AccessKinds AK) {
5028 // If we don't have an lvalue denoting an object of class type, there is no
5029 // meaningful dynamic type. (We consider objects of non-class type to have no
5031 if (!checkDynamicType(Info, E, This, AK, true))
5034 // Refuse to compute a dynamic type in the presence of virtual bases. This
5035 // shouldn't happen other than in constant-folding situations, since literal
5036 // types can't have virtual bases.
5038 // Note that consumers of DynamicType assume that the type has no virtual
5039 // bases, and will need modifications if this restriction is relaxed.
5040 const CXXRecordDecl *Class =
5041 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5042 if (!Class || Class->getNumVBases()) {
5047 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5048 // binary search here instead. But the overwhelmingly common case is that
5049 // we're not in the middle of a constructor, so it probably doesn't matter
5051 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5052 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5053 PathLength <= Path.size(); ++PathLength) {
5054 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5055 Path.slice(0, PathLength))) {
5056 case ConstructionPhase::Bases:
5057 case ConstructionPhase::DestroyingBases:
5058 // We're constructing or destroying a base class. This is not the dynamic
5062 case ConstructionPhase::None:
5063 case ConstructionPhase::AfterBases:
5064 case ConstructionPhase::Destroying:
5065 // We've finished constructing the base classes and not yet started
5066 // destroying them again, so this is the dynamic type.
5067 return DynamicType{getBaseClassType(This.Designator, PathLength),
5072 // CWG issue 1517: we're constructing a base class of the object described by
5073 // 'This', so that object has not yet begun its period of construction and
5074 // any polymorphic operation on it results in undefined behavior.
5079 /// Perform virtual dispatch.
5080 static const CXXMethodDecl *HandleVirtualDispatch(
5081 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5082 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5083 Optional<DynamicType> DynType = ComputeDynamicType(
5085 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5089 // Find the final overrider. It must be declared in one of the classes on the
5090 // path from the dynamic type to the static type.
5091 // FIXME: If we ever allow literal types to have virtual base classes, that
5093 const CXXMethodDecl *Callee = Found;
5094 unsigned PathLength = DynType->PathLength;
5095 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5096 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5097 const CXXMethodDecl *Overrider =
5098 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5105 // C++2a [class.abstract]p6:
5106 // the effect of making a virtual call to a pure virtual function [...] is
5108 if (Callee->isPure()) {
5109 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5110 Info.Note(Callee->getLocation(), diag::note_declared_at);
5114 // If necessary, walk the rest of the path to determine the sequence of
5115 // covariant adjustment steps to apply.
5116 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5117 Found->getReturnType())) {
5118 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5119 for (unsigned CovariantPathLength = PathLength + 1;
5120 CovariantPathLength != This.Designator.Entries.size();
5121 ++CovariantPathLength) {
5122 const CXXRecordDecl *NextClass =
5123 getBaseClassType(This.Designator, CovariantPathLength);
5124 const CXXMethodDecl *Next =
5125 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5126 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5127 Next->getReturnType(), CovariantAdjustmentPath.back()))
5128 CovariantAdjustmentPath.push_back(Next->getReturnType());
5130 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5131 CovariantAdjustmentPath.back()))
5132 CovariantAdjustmentPath.push_back(Found->getReturnType());
5135 // Perform 'this' adjustment.
5136 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5142 /// Perform the adjustment from a value returned by a virtual function to
5143 /// a value of the statically expected type, which may be a pointer or
5144 /// reference to a base class of the returned type.
5145 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5147 ArrayRef<QualType> Path) {
5148 assert(Result.isLValue() &&
5149 "unexpected kind of APValue for covariant return");
5150 if (Result.isNullPointer())
5154 LVal.setFrom(Info.Ctx, Result);
5156 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5157 for (unsigned I = 1; I != Path.size(); ++I) {
5158 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5159 assert(OldClass && NewClass && "unexpected kind of covariant return");
5160 if (OldClass != NewClass &&
5161 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5163 OldClass = NewClass;
5166 LVal.moveInto(Result);
5170 /// Determine whether \p Base, which is known to be a direct base class of
5171 /// \p Derived, is a public base class.
5172 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5173 const CXXRecordDecl *Base) {
5174 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5175 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5176 if (BaseClass && declaresSameEntity(BaseClass, Base))
5177 return BaseSpec.getAccessSpecifier() == AS_public;
5179 llvm_unreachable("Base is not a direct base of Derived");
5182 /// Apply the given dynamic cast operation on the provided lvalue.
5184 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5185 /// to find a suitable target subobject.
5186 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5188 // We can't do anything with a non-symbolic pointer value.
5189 SubobjectDesignator &D = Ptr.Designator;
5193 // C++ [expr.dynamic.cast]p6:
5194 // If v is a null pointer value, the result is a null pointer value.
5195 if (Ptr.isNullPointer() && !E->isGLValue())
5198 // For all the other cases, we need the pointer to point to an object within
5199 // its lifetime / period of construction / destruction, and we need to know
5200 // its dynamic type.
5201 Optional<DynamicType> DynType =
5202 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5206 // C++ [expr.dynamic.cast]p7:
5207 // If T is "pointer to cv void", then the result is a pointer to the most
5209 if (E->getType()->isVoidPointerType())
5210 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5212 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5213 assert(C && "dynamic_cast target is not void pointer nor class");
5214 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5216 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5217 // C++ [expr.dynamic.cast]p9:
5218 if (!E->isGLValue()) {
5219 // The value of a failed cast to pointer type is the null pointer value
5220 // of the required result type.
5221 Ptr.setNull(Info.Ctx, E->getType());
5225 // A failed cast to reference type throws [...] std::bad_cast.
5227 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5228 DynType->Type->isDerivedFrom(C)))
5230 else if (!Paths || Paths->begin() == Paths->end())
5232 else if (Paths->isAmbiguous(CQT))
5235 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5238 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5239 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5240 << Info.Ctx.getRecordType(DynType->Type)
5241 << E->getType().getUnqualifiedType();
5245 // Runtime check, phase 1:
5246 // Walk from the base subobject towards the derived object looking for the
5248 for (int PathLength = Ptr.Designator.Entries.size();
5249 PathLength >= (int)DynType->PathLength; --PathLength) {
5250 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5251 if (declaresSameEntity(Class, C))
5252 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5253 // We can only walk across public inheritance edges.
5254 if (PathLength > (int)DynType->PathLength &&
5255 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5257 return RuntimeCheckFailed(nullptr);
5260 // Runtime check, phase 2:
5261 // Search the dynamic type for an unambiguous public base of type C.
5262 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5263 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5264 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5265 Paths.front().Access == AS_public) {
5266 // Downcast to the dynamic type...
5267 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5269 // ... then upcast to the chosen base class subobject.
5270 for (CXXBasePathElement &Elem : Paths.front())
5271 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5276 // Otherwise, the runtime check fails.
5277 return RuntimeCheckFailed(&Paths);
5281 struct StartLifetimeOfUnionMemberHandler {
5282 const FieldDecl *Field;
5284 static const AccessKinds AccessKind = AK_Assign;
5286 typedef bool result_type;
5287 bool failed() { return false; }
5288 bool found(APValue &Subobj, QualType SubobjType) {
5289 // We are supposed to perform no initialization but begin the lifetime of
5290 // the object. We interpret that as meaning to do what default
5291 // initialization of the object would do if all constructors involved were
5293 // * All base, non-variant member, and array element subobjects' lifetimes
5295 // * No variant members' lifetimes begin
5296 // * All scalar subobjects whose lifetimes begin have indeterminate values
5297 assert(SubobjType->isUnionType());
5298 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5299 !Subobj.getUnionValue().hasValue())
5300 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5303 bool found(APSInt &Value, QualType SubobjType) {
5304 llvm_unreachable("wrong value kind for union object");
5306 bool found(APFloat &Value, QualType SubobjType) {
5307 llvm_unreachable("wrong value kind for union object");
5310 } // end anonymous namespace
5312 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5314 /// Handle a builtin simple-assignment or a call to a trivial assignment
5315 /// operator whose left-hand side might involve a union member access. If it
5316 /// does, implicitly start the lifetime of any accessed union elements per
5317 /// C++20 [class.union]5.
5318 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5319 const LValue &LHS) {
5320 if (LHS.InvalidBase || LHS.Designator.Invalid)
5323 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5324 // C++ [class.union]p5:
5325 // define the set S(E) of subexpressions of E as follows:
5326 unsigned PathLength = LHS.Designator.Entries.size();
5327 for (const Expr *E = LHSExpr; E != nullptr;) {
5328 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5329 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5330 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5331 // Note that we can't implicitly start the lifetime of a reference,
5332 // so we don't need to proceed any further if we reach one.
5333 if (!FD || FD->getType()->isReferenceType())
5336 // ... and also contains A.B if B names a union member
5337 if (FD->getParent()->isUnion())
5338 UnionPathLengths.push_back({PathLength - 1, FD});
5342 assert(declaresSameEntity(FD,
5343 LHS.Designator.Entries[PathLength]
5344 .getAsBaseOrMember().getPointer()));
5346 // -- If E is of the form A[B] and is interpreted as a built-in array
5347 // subscripting operator, S(E) is [S(the array operand, if any)].
5348 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5349 // Step over an ArrayToPointerDecay implicit cast.
5350 auto *Base = ASE->getBase()->IgnoreImplicit();
5351 if (!Base->getType()->isArrayType())
5357 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5358 // Step over a derived-to-base conversion.
5359 E = ICE->getSubExpr();
5360 if (ICE->getCastKind() == CK_NoOp)
5362 if (ICE->getCastKind() != CK_DerivedToBase &&
5363 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5365 // Walk path backwards as we walk up from the base to the derived class.
5366 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5369 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5370 LHS.Designator.Entries[PathLength]
5371 .getAsBaseOrMember().getPointer()));
5374 // -- Otherwise, S(E) is empty.
5380 // Common case: no unions' lifetimes are started.
5381 if (UnionPathLengths.empty())
5384 // if modification of X [would access an inactive union member], an object
5385 // of the type of X is implicitly created
5386 CompleteObject Obj =
5387 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5390 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5391 llvm::reverse(UnionPathLengths)) {
5392 // Form a designator for the union object.
5393 SubobjectDesignator D = LHS.Designator;
5394 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5396 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5397 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5404 /// Determine if a class has any fields that might need to be copied by a
5405 /// trivial copy or move operation.
5406 static bool hasFields(const CXXRecordDecl *RD) {
5407 if (!RD || RD->isEmpty())
5409 for (auto *FD : RD->fields()) {
5410 if (FD->isUnnamedBitfield())
5414 for (auto &Base : RD->bases())
5415 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5421 typedef SmallVector<APValue, 8> ArgVector;
5424 /// EvaluateArgs - Evaluate the arguments to a function call.
5425 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5426 EvalInfo &Info, const FunctionDecl *Callee) {
5427 bool Success = true;
5428 llvm::SmallBitVector ForbiddenNullArgs;
5429 if (Callee->hasAttr<NonNullAttr>()) {
5430 ForbiddenNullArgs.resize(Args.size());
5431 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5432 if (!Attr->args_size()) {
5433 ForbiddenNullArgs.set();
5436 for (auto Idx : Attr->args()) {
5437 unsigned ASTIdx = Idx.getASTIndex();
5438 if (ASTIdx >= Args.size())
5440 ForbiddenNullArgs[ASTIdx] = 1;
5444 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5445 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5446 // If we're checking for a potential constant expression, evaluate all
5447 // initializers even if some of them fail.
5448 if (!Info.noteFailure())
5451 } else if (!ForbiddenNullArgs.empty() &&
5452 ForbiddenNullArgs[Idx] &&
5453 ArgValues[Idx].isLValue() &&
5454 ArgValues[Idx].isNullPointer()) {
5455 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5456 if (!Info.noteFailure())
5464 /// Evaluate a function call.
5465 static bool HandleFunctionCall(SourceLocation CallLoc,
5466 const FunctionDecl *Callee, const LValue *This,
5467 ArrayRef<const Expr*> Args, const Stmt *Body,
5468 EvalInfo &Info, APValue &Result,
5469 const LValue *ResultSlot) {
5470 ArgVector ArgValues(Args.size());
5471 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5474 if (!Info.CheckCallLimit(CallLoc))
5477 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5479 // For a trivial copy or move assignment, perform an APValue copy. This is
5480 // essential for unions, where the operations performed by the assignment
5481 // operator cannot be represented as statements.
5483 // Skip this for non-union classes with no fields; in that case, the defaulted
5484 // copy/move does not actually read the object.
5485 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5486 if (MD && MD->isDefaulted() &&
5487 (MD->getParent()->isUnion() ||
5488 (MD->isTrivial() && hasFields(MD->getParent())))) {
5490 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5492 RHS.setFrom(Info.Ctx, ArgValues[0]);
5494 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5495 RHSValue, MD->getParent()->isUnion()))
5497 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5498 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5500 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5503 This->moveInto(Result);
5505 } else if (MD && isLambdaCallOperator(MD)) {
5506 // We're in a lambda; determine the lambda capture field maps unless we're
5507 // just constexpr checking a lambda's call operator. constexpr checking is
5508 // done before the captures have been added to the closure object (unless
5509 // we're inferring constexpr-ness), so we don't have access to them in this
5510 // case. But since we don't need the captures to constexpr check, we can
5511 // just ignore them.
5512 if (!Info.checkingPotentialConstantExpression())
5513 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5514 Frame.LambdaThisCaptureField);
5517 StmtResult Ret = {Result, ResultSlot};
5518 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5519 if (ESR == ESR_Succeeded) {
5520 if (Callee->getReturnType()->isVoidType())
5522 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5524 return ESR == ESR_Returned;
5527 /// Evaluate a constructor call.
5528 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5530 const CXXConstructorDecl *Definition,
5531 EvalInfo &Info, APValue &Result) {
5532 SourceLocation CallLoc = E->getExprLoc();
5533 if (!Info.CheckCallLimit(CallLoc))
5536 const CXXRecordDecl *RD = Definition->getParent();
5537 if (RD->getNumVBases()) {
5538 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5542 EvalInfo::EvaluatingConstructorRAII EvalObj(
5544 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5546 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5548 // FIXME: Creating an APValue just to hold a nonexistent return value is
5551 StmtResult Ret = {RetVal, nullptr};
5553 // If it's a delegating constructor, delegate.
5554 if (Definition->isDelegatingConstructor()) {
5555 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5557 FullExpressionRAII InitScope(Info);
5558 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5559 !InitScope.destroy())
5562 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5565 // For a trivial copy or move constructor, perform an APValue copy. This is
5566 // essential for unions (or classes with anonymous union members), where the
5567 // operations performed by the constructor cannot be represented by
5568 // ctor-initializers.
5570 // Skip this for empty non-union classes; we should not perform an
5571 // lvalue-to-rvalue conversion on them because their copy constructor does not
5572 // actually read them.
5573 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5574 (Definition->getParent()->isUnion() ||
5575 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5577 RHS.setFrom(Info.Ctx, ArgValues[0]);
5578 return handleLValueToRValueConversion(
5579 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5580 RHS, Result, Definition->getParent()->isUnion());
5583 // Reserve space for the struct members.
5584 if (!RD->isUnion() && !Result.hasValue())
5585 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5586 std::distance(RD->field_begin(), RD->field_end()));
5588 if (RD->isInvalidDecl()) return false;
5589 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5591 // A scope for temporaries lifetime-extended by reference members.
5592 BlockScopeRAII LifetimeExtendedScope(Info);
5594 bool Success = true;
5595 unsigned BasesSeen = 0;
5597 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5599 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5600 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5601 // We might be initializing the same field again if this is an indirect
5602 // field initialization.
5603 if (FieldIt == RD->field_end() ||
5604 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5605 assert(Indirect && "fields out of order?");
5609 // Default-initialize any fields with no explicit initializer.
5610 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5611 assert(FieldIt != RD->field_end() && "missing field?");
5612 if (!FieldIt->isUnnamedBitfield())
5613 Result.getStructField(FieldIt->getFieldIndex()) =
5614 getDefaultInitValue(FieldIt->getType());
5618 for (const auto *I : Definition->inits()) {
5619 LValue Subobject = This;
5620 LValue SubobjectParent = This;
5621 APValue *Value = &Result;
5623 // Determine the subobject to initialize.
5624 FieldDecl *FD = nullptr;
5625 if (I->isBaseInitializer()) {
5626 QualType BaseType(I->getBaseClass(), 0);
5628 // Non-virtual base classes are initialized in the order in the class
5629 // definition. We have already checked for virtual base classes.
5630 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5631 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5632 "base class initializers not in expected order");
5635 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5636 BaseType->getAsCXXRecordDecl(), &Layout))
5638 Value = &Result.getStructBase(BasesSeen++);
5639 } else if ((FD = I->getMember())) {
5640 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5642 if (RD->isUnion()) {
5643 Result = APValue(FD);
5644 Value = &Result.getUnionValue();
5646 SkipToField(FD, false);
5647 Value = &Result.getStructField(FD->getFieldIndex());
5649 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5650 // Walk the indirect field decl's chain to find the object to initialize,
5651 // and make sure we've initialized every step along it.
5652 auto IndirectFieldChain = IFD->chain();
5653 for (auto *C : IndirectFieldChain) {
5654 FD = cast<FieldDecl>(C);
5655 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5656 // Switch the union field if it differs. This happens if we had
5657 // preceding zero-initialization, and we're now initializing a union
5658 // subobject other than the first.
5659 // FIXME: In this case, the values of the other subobjects are
5660 // specified, since zero-initialization sets all padding bits to zero.
5661 if (!Value->hasValue() ||
5662 (Value->isUnion() && Value->getUnionField() != FD)) {
5664 *Value = APValue(FD);
5666 // FIXME: This immediately starts the lifetime of all members of an
5667 // anonymous struct. It would be preferable to strictly start member
5668 // lifetime in initialization order.
5669 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5671 // Store Subobject as its parent before updating it for the last element
5673 if (C == IndirectFieldChain.back())
5674 SubobjectParent = Subobject;
5675 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5678 Value = &Value->getUnionValue();
5680 if (C == IndirectFieldChain.front() && !RD->isUnion())
5681 SkipToField(FD, true);
5682 Value = &Value->getStructField(FD->getFieldIndex());
5686 llvm_unreachable("unknown base initializer kind");
5689 // Need to override This for implicit field initializers as in this case
5690 // This refers to innermost anonymous struct/union containing initializer,
5691 // not to currently constructed class.
5692 const Expr *Init = I->getInit();
5693 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5694 isa<CXXDefaultInitExpr>(Init));
5695 FullExpressionRAII InitScope(Info);
5696 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5697 (FD && FD->isBitField() &&
5698 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5699 // If we're checking for a potential constant expression, evaluate all
5700 // initializers even if some of them fail.
5701 if (!Info.noteFailure())
5706 // This is the point at which the dynamic type of the object becomes this
5708 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5709 EvalObj.finishedConstructingBases();
5712 // Default-initialize any remaining fields.
5713 if (!RD->isUnion()) {
5714 for (; FieldIt != RD->field_end(); ++FieldIt) {
5715 if (!FieldIt->isUnnamedBitfield())
5716 Result.getStructField(FieldIt->getFieldIndex()) =
5717 getDefaultInitValue(FieldIt->getType());
5722 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5723 LifetimeExtendedScope.destroy();
5726 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5727 ArrayRef<const Expr*> Args,
5728 const CXXConstructorDecl *Definition,
5729 EvalInfo &Info, APValue &Result) {
5730 ArgVector ArgValues(Args.size());
5731 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5734 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5738 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5739 const LValue &This, APValue &Value,
5741 // Objects can only be destroyed while they're within their lifetimes.
5742 // FIXME: We have no representation for whether an object of type nullptr_t
5743 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5744 // as indeterminate instead?
5745 if (Value.isAbsent() && !T->isNullPtrType()) {
5747 This.moveInto(Printable);
5748 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5749 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5753 // Invent an expression for location purposes.
5754 // FIXME: We shouldn't need to do this.
5755 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5757 // For arrays, destroy elements right-to-left.
5758 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5759 uint64_t Size = CAT->getSize().getZExtValue();
5760 QualType ElemT = CAT->getElementType();
5762 LValue ElemLV = This;
5763 ElemLV.addArray(Info, &LocE, CAT);
5764 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5767 // Ensure that we have actual array elements available to destroy; the
5768 // destructors might mutate the value, so we can't run them on the array
5770 if (Size && Size > Value.getArrayInitializedElts())
5771 expandArray(Value, Value.getArraySize() - 1);
5773 for (; Size != 0; --Size) {
5774 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5775 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5776 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5780 // End the lifetime of this array now.
5785 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5787 if (T.isDestructedType()) {
5788 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5796 if (RD->getNumVBases()) {
5797 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5801 const CXXDestructorDecl *DD = RD->getDestructor();
5802 if (!DD && !RD->hasTrivialDestructor()) {
5803 Info.FFDiag(CallLoc);
5807 if (!DD || DD->isTrivial() ||
5808 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5809 // A trivial destructor just ends the lifetime of the object. Check for
5810 // this case before checking for a body, because we might not bother
5811 // building a body for a trivial destructor. Note that it doesn't matter
5812 // whether the destructor is constexpr in this case; all trivial
5813 // destructors are constexpr.
5815 // If an anonymous union would be destroyed, some enclosing destructor must
5816 // have been explicitly defined, and the anonymous union destruction should
5822 if (!Info.CheckCallLimit(CallLoc))
5825 const FunctionDecl *Definition = nullptr;
5826 const Stmt *Body = DD->getBody(Definition);
5828 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5831 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5833 // We're now in the period of destruction of this object.
5834 unsigned BasesLeft = RD->getNumBases();
5835 EvalInfo::EvaluatingDestructorRAII EvalObj(
5837 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5838 if (!EvalObj.DidInsert) {
5839 // C++2a [class.dtor]p19:
5840 // the behavior is undefined if the destructor is invoked for an object
5841 // whose lifetime has ended
5842 // (Note that formally the lifetime ends when the period of destruction
5843 // begins, even though certain uses of the object remain valid until the
5844 // period of destruction ends.)
5845 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5849 // FIXME: Creating an APValue just to hold a nonexistent return value is
5852 StmtResult Ret = {RetVal, nullptr};
5853 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5856 // A union destructor does not implicitly destroy its members.
5860 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5862 // We don't have a good way to iterate fields in reverse, so collect all the
5863 // fields first and then walk them backwards.
5864 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5865 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5866 if (FD->isUnnamedBitfield())
5869 LValue Subobject = This;
5870 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5873 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5874 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5880 EvalObj.startedDestroyingBases();
5882 // Destroy base classes in reverse order.
5883 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5886 QualType BaseType = Base.getType();
5887 LValue Subobject = This;
5888 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5889 BaseType->getAsCXXRecordDecl(), &Layout))
5892 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5893 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5897 assert(BasesLeft == 0 && "NumBases was wrong?");
5899 // The period of destruction ends now. The object is gone.
5905 struct DestroyObjectHandler {
5909 const AccessKinds AccessKind;
5911 typedef bool result_type;
5912 bool failed() { return false; }
5913 bool found(APValue &Subobj, QualType SubobjType) {
5914 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5917 bool found(APSInt &Value, QualType SubobjType) {
5918 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5921 bool found(APFloat &Value, QualType SubobjType) {
5922 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5928 /// Perform a destructor or pseudo-destructor call on the given object, which
5929 /// might in general not be a complete object.
5930 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5931 const LValue &This, QualType ThisType) {
5932 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5933 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5934 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5937 /// Destroy and end the lifetime of the given complete object.
5938 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5939 APValue::LValueBase LVBase, APValue &Value,
5941 // If we've had an unmodeled side-effect, we can't rely on mutable state
5942 // (such as the object we're about to destroy) being correct.
5943 if (Info.EvalStatus.HasSideEffects)
5948 return HandleDestructionImpl(Info, Loc, LV, Value, T);
5951 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
5952 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
5954 if (Info.checkingPotentialConstantExpression() ||
5955 Info.SpeculativeEvaluationDepth)
5958 // This is permitted only within a call to std::allocator<T>::allocate.
5959 auto Caller = Info.getStdAllocatorCaller("allocate");
5961 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
5962 ? diag::note_constexpr_new_untyped
5963 : diag::note_constexpr_new);
5967 QualType ElemType = Caller.ElemType;
5968 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
5969 Info.FFDiag(E->getExprLoc(),
5970 diag::note_constexpr_new_not_complete_object_type)
5971 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
5976 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
5978 bool IsNothrow = false;
5979 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
5980 EvaluateIgnoredValue(Info, E->getArg(I));
5981 IsNothrow |= E->getType()->isNothrowT();
5985 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
5987 APInt Size, Remainder;
5988 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
5989 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
5990 if (Remainder != 0) {
5991 // This likely indicates a bug in the implementation of 'std::allocator'.
5992 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
5993 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
5997 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
5999 Result.setNull(Info.Ctx, E->getType());
6003 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6007 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6008 ArrayType::Normal, 0);
6009 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6010 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6011 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6015 static bool hasVirtualDestructor(QualType T) {
6016 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6017 if (CXXDestructorDecl *DD = RD->getDestructor())
6018 return DD->isVirtual();
6022 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6023 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6024 if (CXXDestructorDecl *DD = RD->getDestructor())
6025 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6029 /// Check that the given object is a suitable pointer to a heap allocation that
6030 /// still exists and is of the right kind for the purpose of a deletion.
6032 /// On success, returns the heap allocation to deallocate. On failure, produces
6033 /// a diagnostic and returns None.
6034 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6035 const LValue &Pointer,
6036 DynAlloc::Kind DeallocKind) {
6037 auto PointerAsString = [&] {
6038 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6041 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6043 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6044 << PointerAsString();
6046 NoteLValueLocation(Info, Pointer.Base);
6050 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6052 Info.FFDiag(E, diag::note_constexpr_double_delete);
6056 QualType AllocType = Pointer.Base.getDynamicAllocType();
6057 if (DeallocKind != (*Alloc)->getKind()) {
6058 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6059 << DeallocKind << (*Alloc)->getKind() << AllocType;
6060 NoteLValueLocation(Info, Pointer.Base);
6064 bool Subobject = false;
6065 if (DeallocKind == DynAlloc::New) {
6066 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6067 Pointer.Designator.isOnePastTheEnd();
6069 Subobject = Pointer.Designator.Entries.size() != 1 ||
6070 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6073 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6074 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6081 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6082 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6083 if (Info.checkingPotentialConstantExpression() ||
6084 Info.SpeculativeEvaluationDepth)
6087 // This is permitted only within a call to std::allocator<T>::deallocate.
6088 if (!Info.getStdAllocatorCaller("deallocate")) {
6089 Info.FFDiag(E->getExprLoc());
6094 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6096 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6097 EvaluateIgnoredValue(Info, E->getArg(I));
6099 if (Pointer.Designator.Invalid)
6102 // Deleting a null pointer has no effect.
6103 if (Pointer.isNullPointer())
6106 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6109 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6113 //===----------------------------------------------------------------------===//
6114 // Generic Evaluation
6115 //===----------------------------------------------------------------------===//
6118 class BitCastBuffer {
6119 // FIXME: We're going to need bit-level granularity when we support
6121 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6122 // we don't support a host or target where that is the case. Still, we should
6123 // use a more generic type in case we ever do.
6124 SmallVector<Optional<unsigned char>, 32> Bytes;
6126 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6127 "Need at least 8 bit unsigned char");
6129 bool TargetIsLittleEndian;
6132 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6133 : Bytes(Width.getQuantity()),
6134 TargetIsLittleEndian(TargetIsLittleEndian) {}
6137 bool readObject(CharUnits Offset, CharUnits Width,
6138 SmallVectorImpl<unsigned char> &Output) const {
6139 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6140 // If a byte of an integer is uninitialized, then the whole integer is
6142 if (!Bytes[I.getQuantity()])
6144 Output.push_back(*Bytes[I.getQuantity()]);
6146 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6147 std::reverse(Output.begin(), Output.end());
6151 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6152 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6153 std::reverse(Input.begin(), Input.end());
6156 for (unsigned char Byte : Input) {
6157 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6158 Bytes[Offset.getQuantity() + Index] = Byte;
6163 size_t size() { return Bytes.size(); }
6166 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6167 /// target would represent the value at runtime.
6168 class APValueToBufferConverter {
6170 BitCastBuffer Buffer;
6171 const CastExpr *BCE;
6173 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6174 const CastExpr *BCE)
6176 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6179 bool visit(const APValue &Val, QualType Ty) {
6180 return visit(Val, Ty, CharUnits::fromQuantity(0));
6183 // Write out Val with type Ty into Buffer starting at Offset.
6184 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6185 assert((size_t)Offset.getQuantity() <= Buffer.size());
6187 // As a special case, nullptr_t has an indeterminate value.
6188 if (Ty->isNullPtrType())
6191 // Dig through Src to find the byte at SrcOffset.
6192 switch (Val.getKind()) {
6193 case APValue::Indeterminate:
6198 return visitInt(Val.getInt(), Ty, Offset);
6199 case APValue::Float:
6200 return visitFloat(Val.getFloat(), Ty, Offset);
6201 case APValue::Array:
6202 return visitArray(Val, Ty, Offset);
6203 case APValue::Struct:
6204 return visitRecord(Val, Ty, Offset);
6206 case APValue::ComplexInt:
6207 case APValue::ComplexFloat:
6208 case APValue::Vector:
6209 case APValue::FixedPoint:
6210 // FIXME: We should support these.
6212 case APValue::Union:
6213 case APValue::MemberPointer:
6214 case APValue::AddrLabelDiff: {
6215 Info.FFDiag(BCE->getBeginLoc(),
6216 diag::note_constexpr_bit_cast_unsupported_type)
6221 case APValue::LValue:
6222 llvm_unreachable("LValue subobject in bit_cast?");
6224 llvm_unreachable("Unhandled APValue::ValueKind");
6227 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6228 const RecordDecl *RD = Ty->getAsRecordDecl();
6229 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6231 // Visit the base classes.
6232 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6233 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6234 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6235 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6237 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6238 Layout.getBaseClassOffset(BaseDecl) + Offset))
6243 // Visit the fields.
6244 unsigned FieldIdx = 0;
6245 for (FieldDecl *FD : RD->fields()) {
6246 if (FD->isBitField()) {
6247 Info.FFDiag(BCE->getBeginLoc(),
6248 diag::note_constexpr_bit_cast_unsupported_bitfield);
6252 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6254 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6255 "only bit-fields can have sub-char alignment");
6256 CharUnits FieldOffset =
6257 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6258 QualType FieldTy = FD->getType();
6259 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6267 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6269 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6273 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6274 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6275 unsigned ArraySize = Val.getArraySize();
6276 // First, initialize the initialized elements.
6277 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6278 const APValue &SubObj = Val.getArrayInitializedElt(I);
6279 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6283 // Next, initialize the rest of the array using the filler.
6284 if (Val.hasArrayFiller()) {
6285 const APValue &Filler = Val.getArrayFiller();
6286 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6287 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6295 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6296 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6297 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6298 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6299 Buffer.writeObject(Offset, Bytes);
6303 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6304 APSInt AsInt(Val.bitcastToAPInt());
6305 return visitInt(AsInt, Ty, Offset);
6309 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6310 const CastExpr *BCE) {
6311 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6312 APValueToBufferConverter Converter(Info, DstSize, BCE);
6313 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6315 return Converter.Buffer;
6319 /// Write an BitCastBuffer into an APValue.
6320 class BufferToAPValueConverter {
6322 const BitCastBuffer &Buffer;
6323 const CastExpr *BCE;
6325 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6326 const CastExpr *BCE)
6327 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6329 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6330 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6331 // Ideally this will be unreachable.
6332 llvm::NoneType unsupportedType(QualType Ty) {
6333 Info.FFDiag(BCE->getBeginLoc(),
6334 diag::note_constexpr_bit_cast_unsupported_type)
6339 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6340 const EnumType *EnumSugar = nullptr) {
6341 if (T->isNullPtrType()) {
6342 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6343 return APValue((Expr *)nullptr,
6344 /*Offset=*/CharUnits::fromQuantity(NullValue),
6345 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6348 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6349 SmallVector<uint8_t, 8> Bytes;
6350 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6351 // If this is std::byte or unsigned char, then its okay to store an
6352 // indeterminate value.
6353 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6355 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6356 T->isSpecificBuiltinType(BuiltinType::Char_U));
6357 if (!IsStdByte && !IsUChar) {
6358 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6359 Info.FFDiag(BCE->getExprLoc(),
6360 diag::note_constexpr_bit_cast_indet_dest)
6361 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6365 return APValue::IndeterminateValue();
6368 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6369 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6371 if (T->isIntegralOrEnumerationType()) {
6372 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6373 return APValue(Val);
6376 if (T->isRealFloatingType()) {
6377 const llvm::fltSemantics &Semantics =
6378 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6379 return APValue(APFloat(Semantics, Val));
6382 return unsupportedType(QualType(T, 0));
6385 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6386 const RecordDecl *RD = RTy->getAsRecordDecl();
6387 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6389 unsigned NumBases = 0;
6390 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6391 NumBases = CXXRD->getNumBases();
6393 APValue ResultVal(APValue::UninitStruct(), NumBases,
6394 std::distance(RD->field_begin(), RD->field_end()));
6396 // Visit the base classes.
6397 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6398 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6399 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6400 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6401 if (BaseDecl->isEmpty() ||
6402 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6405 Optional<APValue> SubObj = visitType(
6406 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6409 ResultVal.getStructBase(I) = *SubObj;
6413 // Visit the fields.
6414 unsigned FieldIdx = 0;
6415 for (FieldDecl *FD : RD->fields()) {
6416 // FIXME: We don't currently support bit-fields. A lot of the logic for
6417 // this is in CodeGen, so we need to factor it around.
6418 if (FD->isBitField()) {
6419 Info.FFDiag(BCE->getBeginLoc(),
6420 diag::note_constexpr_bit_cast_unsupported_bitfield);
6424 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6425 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6427 CharUnits FieldOffset =
6428 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6430 QualType FieldTy = FD->getType();
6431 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6434 ResultVal.getStructField(FieldIdx) = *SubObj;
6441 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6442 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6443 assert(!RepresentationType.isNull() &&
6444 "enum forward decl should be caught by Sema");
6445 const auto *AsBuiltin =
6446 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6447 // Recurse into the underlying type. Treat std::byte transparently as
6449 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6452 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6453 size_t Size = Ty->getSize().getLimitedValue();
6454 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6456 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6457 for (size_t I = 0; I != Size; ++I) {
6458 Optional<APValue> ElementValue =
6459 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6462 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6468 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6469 return unsupportedType(QualType(Ty, 0));
6472 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6473 QualType Can = Ty.getCanonicalType();
6475 switch (Can->getTypeClass()) {
6476 #define TYPE(Class, Base) \
6478 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6479 #define ABSTRACT_TYPE(Class, Base)
6480 #define NON_CANONICAL_TYPE(Class, Base) \
6482 llvm_unreachable("non-canonical type should be impossible!");
6483 #define DEPENDENT_TYPE(Class, Base) \
6486 "dependent types aren't supported in the constant evaluator!");
6487 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
6489 llvm_unreachable("either dependent or not canonical!");
6490 #include "clang/AST/TypeNodes.inc"
6492 llvm_unreachable("Unhandled Type::TypeClass");
6496 // Pull out a full value of type DstType.
6497 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6498 const CastExpr *BCE) {
6499 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6500 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6504 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6505 QualType Ty, EvalInfo *Info,
6506 const ASTContext &Ctx,
6507 bool CheckingDest) {
6508 Ty = Ty.getCanonicalType();
6510 auto diag = [&](int Reason) {
6512 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6513 << CheckingDest << (Reason == 4) << Reason;
6516 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6518 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6519 << NoteTy << Construct << Ty;
6523 if (Ty->isUnionType())
6525 if (Ty->isPointerType())
6527 if (Ty->isMemberPointerType())
6529 if (Ty.isVolatileQualified())
6532 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6533 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6534 for (CXXBaseSpecifier &BS : CXXRD->bases())
6535 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6537 return note(1, BS.getType(), BS.getBeginLoc());
6539 for (FieldDecl *FD : Record->fields()) {
6540 if (FD->getType()->isReferenceType())
6542 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6544 return note(0, FD->getType(), FD->getBeginLoc());
6548 if (Ty->isArrayType() &&
6549 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6550 Info, Ctx, CheckingDest))
6556 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6557 const ASTContext &Ctx,
6558 const CastExpr *BCE) {
6559 bool DestOK = checkBitCastConstexprEligibilityType(
6560 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6561 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6563 BCE->getSubExpr()->getType(), Info, Ctx, false);
6567 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6568 APValue &SourceValue,
6569 const CastExpr *BCE) {
6570 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6571 "no host or target supports non 8-bit chars");
6572 assert(SourceValue.isLValue() &&
6573 "LValueToRValueBitcast requires an lvalue operand!");
6575 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6578 LValue SourceLValue;
6579 APValue SourceRValue;
6580 SourceLValue.setFrom(Info.Ctx, SourceValue);
6581 if (!handleLValueToRValueConversion(
6582 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6583 SourceRValue, /*WantObjectRepresentation=*/true))
6586 // Read out SourceValue into a char buffer.
6587 Optional<BitCastBuffer> Buffer =
6588 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6592 // Write out the buffer into a new APValue.
6593 Optional<APValue> MaybeDestValue =
6594 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6595 if (!MaybeDestValue)
6598 DestValue = std::move(*MaybeDestValue);
6602 template <class Derived>
6603 class ExprEvaluatorBase
6604 : public ConstStmtVisitor<Derived, bool> {
6606 Derived &getDerived() { return static_cast<Derived&>(*this); }
6607 bool DerivedSuccess(const APValue &V, const Expr *E) {
6608 return getDerived().Success(V, E);
6610 bool DerivedZeroInitialization(const Expr *E) {
6611 return getDerived().ZeroInitialization(E);
6614 // Check whether a conditional operator with a non-constant condition is a
6615 // potential constant expression. If neither arm is a potential constant
6616 // expression, then the conditional operator is not either.
6617 template<typename ConditionalOperator>
6618 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6619 assert(Info.checkingPotentialConstantExpression());
6621 // Speculatively evaluate both arms.
6622 SmallVector<PartialDiagnosticAt, 8> Diag;
6624 SpeculativeEvaluationRAII Speculate(Info, &Diag);
6625 StmtVisitorTy::Visit(E->getFalseExpr());
6631 SpeculativeEvaluationRAII Speculate(Info, &Diag);
6633 StmtVisitorTy::Visit(E->getTrueExpr());
6638 Error(E, diag::note_constexpr_conditional_never_const);
6642 template<typename ConditionalOperator>
6643 bool HandleConditionalOperator(const ConditionalOperator *E) {
6645 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6646 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6647 CheckPotentialConstantConditional(E);
6650 if (Info.noteFailure()) {
6651 StmtVisitorTy::Visit(E->getTrueExpr());
6652 StmtVisitorTy::Visit(E->getFalseExpr());
6657 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6658 return StmtVisitorTy::Visit(EvalExpr);
6663 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6664 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6666 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6667 return Info.CCEDiag(E, D);
6670 bool ZeroInitialization(const Expr *E) { return Error(E); }
6673 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6675 EvalInfo &getEvalInfo() { return Info; }
6677 /// Report an evaluation error. This should only be called when an error is
6678 /// first discovered. When propagating an error, just return false.
6679 bool Error(const Expr *E, diag::kind D) {
6683 bool Error(const Expr *E) {
6684 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6687 bool VisitStmt(const Stmt *) {
6688 llvm_unreachable("Expression evaluator should not be called on stmts");
6690 bool VisitExpr(const Expr *E) {
6694 bool VisitConstantExpr(const ConstantExpr *E)
6695 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6696 bool VisitParenExpr(const ParenExpr *E)
6697 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6698 bool VisitUnaryExtension(const UnaryOperator *E)
6699 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6700 bool VisitUnaryPlus(const UnaryOperator *E)
6701 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6702 bool VisitChooseExpr(const ChooseExpr *E)
6703 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6704 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6705 { return StmtVisitorTy::Visit(E->getResultExpr()); }
6706 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6707 { return StmtVisitorTy::Visit(E->getReplacement()); }
6708 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6709 TempVersionRAII RAII(*Info.CurrentCall);
6710 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6711 return StmtVisitorTy::Visit(E->getExpr());
6713 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6714 TempVersionRAII RAII(*Info.CurrentCall);
6715 // The initializer may not have been parsed yet, or might be erroneous.
6718 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6719 return StmtVisitorTy::Visit(E->getExpr());
6722 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6723 FullExpressionRAII Scope(Info);
6724 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6727 // Temporaries are registered when created, so we don't care about
6728 // CXXBindTemporaryExpr.
6729 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6730 return StmtVisitorTy::Visit(E->getSubExpr());
6733 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6734 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6735 return static_cast<Derived*>(this)->VisitCastExpr(E);
6737 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6738 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6739 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6740 return static_cast<Derived*>(this)->VisitCastExpr(E);
6742 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6743 return static_cast<Derived*>(this)->VisitCastExpr(E);
6746 bool VisitBinaryOperator(const BinaryOperator *E) {
6747 switch (E->getOpcode()) {
6752 VisitIgnoredValue(E->getLHS());
6753 return StmtVisitorTy::Visit(E->getRHS());
6758 if (!HandleMemberPointerAccess(Info, E, Obj))
6761 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6763 return DerivedSuccess(Result, E);
6768 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6769 return StmtVisitorTy::Visit(E->getSemanticForm());
6772 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6773 // Evaluate and cache the common expression. We treat it as a temporary,
6774 // even though it's not quite the same thing.
6776 if (!Evaluate(Info.CurrentCall->createTemporary(
6777 E->getOpaqueValue(),
6778 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6780 Info, E->getCommon()))
6783 return HandleConditionalOperator(E);
6786 bool VisitConditionalOperator(const ConditionalOperator *E) {
6787 bool IsBcpCall = false;
6788 // If the condition (ignoring parens) is a __builtin_constant_p call,
6789 // the result is a constant expression if it can be folded without
6790 // side-effects. This is an important GNU extension. See GCC PR38377
6792 if (const CallExpr *CallCE =
6793 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6794 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6797 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6798 // constant expression; we can't check whether it's potentially foldable.
6799 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6800 // it would return 'false' in this mode.
6801 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6804 FoldConstant Fold(Info, IsBcpCall);
6805 if (!HandleConditionalOperator(E)) {
6806 Fold.keepDiagnostics();
6813 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6814 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6815 return DerivedSuccess(*Value, E);
6817 const Expr *Source = E->getSourceExpr();
6820 if (Source == E) { // sanity checking.
6821 assert(0 && "OpaqueValueExpr recursively refers to itself");
6824 return StmtVisitorTy::Visit(Source);
6827 bool VisitCallExpr(const CallExpr *E) {
6829 if (!handleCallExpr(E, Result, nullptr))
6831 return DerivedSuccess(Result, E);
6834 bool handleCallExpr(const CallExpr *E, APValue &Result,
6835 const LValue *ResultSlot) {
6836 const Expr *Callee = E->getCallee()->IgnoreParens();
6837 QualType CalleeType = Callee->getType();
6839 const FunctionDecl *FD = nullptr;
6840 LValue *This = nullptr, ThisVal;
6841 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6842 bool HasQualifier = false;
6844 // Extract function decl and 'this' pointer from the callee.
6845 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6846 const CXXMethodDecl *Member = nullptr;
6847 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6848 // Explicit bound member calls, such as x.f() or p->g();
6849 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6851 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6853 return Error(Callee);
6855 HasQualifier = ME->hasQualifier();
6856 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6857 // Indirect bound member calls ('.*' or '->*').
6858 const ValueDecl *D =
6859 HandleMemberPointerAccess(Info, BE, ThisVal, false);
6862 Member = dyn_cast<CXXMethodDecl>(D);
6864 return Error(Callee);
6866 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6867 if (!Info.getLangOpts().CPlusPlus2a)
6868 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6869 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6870 // their callee, we should start calling HandleDestruction here.
6871 // For now, we just evaluate the object argument and discard it.
6872 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
6874 return Error(Callee);
6876 } else if (CalleeType->isFunctionPointerType()) {
6878 if (!EvaluatePointer(Callee, Call, Info))
6881 if (!Call.getLValueOffset().isZero())
6882 return Error(Callee);
6883 FD = dyn_cast_or_null<FunctionDecl>(
6884 Call.getLValueBase().dyn_cast<const ValueDecl*>());
6886 return Error(Callee);
6887 // Don't call function pointers which have been cast to some other type.
6888 // Per DR (no number yet), the caller and callee can differ in noexcept.
6889 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6890 CalleeType->getPointeeType(), FD->getType())) {
6894 // Overloaded operator calls to member functions are represented as normal
6895 // calls with '*this' as the first argument.
6896 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6897 if (MD && !MD->isStatic()) {
6898 // FIXME: When selecting an implicit conversion for an overloaded
6899 // operator delete, we sometimes try to evaluate calls to conversion
6900 // operators without a 'this' parameter!
6904 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6907 Args = Args.slice(1);
6908 } else if (MD && MD->isLambdaStaticInvoker()) {
6909 // Map the static invoker for the lambda back to the call operator.
6910 // Conveniently, we don't have to slice out the 'this' argument (as is
6911 // being done for the non-static case), since a static member function
6912 // doesn't have an implicit argument passed in.
6913 const CXXRecordDecl *ClosureClass = MD->getParent();
6915 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6916 "Number of captures must be zero for conversion to function-ptr");
6918 const CXXMethodDecl *LambdaCallOp =
6919 ClosureClass->getLambdaCallOperator();
6921 // Set 'FD', the function that will be called below, to the call
6922 // operator. If the closure object represents a generic lambda, find
6923 // the corresponding specialization of the call operator.
6925 if (ClosureClass->isGenericLambda()) {
6926 assert(MD->isFunctionTemplateSpecialization() &&
6927 "A generic lambda's static-invoker function must be a "
6928 "template specialization");
6929 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6930 FunctionTemplateDecl *CallOpTemplate =
6931 LambdaCallOp->getDescribedFunctionTemplate();
6932 void *InsertPos = nullptr;
6933 FunctionDecl *CorrespondingCallOpSpecialization =
6934 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6935 assert(CorrespondingCallOpSpecialization &&
6936 "We must always have a function call operator specialization "
6937 "that corresponds to our static invoker specialization");
6938 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6941 } else if (FD->isReplaceableGlobalAllocationFunction()) {
6942 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
6943 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
6945 if (!HandleOperatorNewCall(Info, E, Ptr))
6947 Ptr.moveInto(Result);
6950 return HandleOperatorDeleteCall(Info, E);
6956 SmallVector<QualType, 4> CovariantAdjustmentPath;
6958 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6959 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6960 // Perform virtual dispatch, if necessary.
6961 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6962 CovariantAdjustmentPath);
6966 // Check that the 'this' pointer points to an object of the right type.
6967 // FIXME: If this is an assignment operator call, we may need to change
6968 // the active union member before we check this.
6969 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
6974 // Destructor calls are different enough that they have their own codepath.
6975 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
6976 assert(This && "no 'this' pointer for destructor call");
6977 return HandleDestruction(Info, E, *This,
6978 Info.Ctx.getRecordType(DD->getParent()));
6981 const FunctionDecl *Definition = nullptr;
6982 Stmt *Body = FD->getBody(Definition);
6984 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6985 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6986 Result, ResultSlot))
6989 if (!CovariantAdjustmentPath.empty() &&
6990 !HandleCovariantReturnAdjustment(Info, E, Result,
6991 CovariantAdjustmentPath))
6997 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6998 return StmtVisitorTy::Visit(E->getInitializer());
7000 bool VisitInitListExpr(const InitListExpr *E) {
7001 if (E->getNumInits() == 0)
7002 return DerivedZeroInitialization(E);
7003 if (E->getNumInits() == 1)
7004 return StmtVisitorTy::Visit(E->getInit(0));
7007 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7008 return DerivedZeroInitialization(E);
7010 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7011 return DerivedZeroInitialization(E);
7013 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7014 return DerivedZeroInitialization(E);
7017 /// A member expression where the object is a prvalue is itself a prvalue.
7018 bool VisitMemberExpr(const MemberExpr *E) {
7019 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7020 "missing temporary materialization conversion");
7021 assert(!E->isArrow() && "missing call to bound member function?");
7024 if (!Evaluate(Val, Info, E->getBase()))
7027 QualType BaseTy = E->getBase()->getType();
7029 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7030 if (!FD) return Error(E);
7031 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7032 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7033 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7035 // Note: there is no lvalue base here. But this case should only ever
7036 // happen in C or in C++98, where we cannot be evaluating a constexpr
7037 // constructor, which is the only case the base matters.
7038 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7039 SubobjectDesignator Designator(BaseTy);
7040 Designator.addDeclUnchecked(FD);
7043 return extractSubobject(Info, E, Obj, Designator, Result) &&
7044 DerivedSuccess(Result, E);
7047 bool VisitCastExpr(const CastExpr *E) {
7048 switch (E->getCastKind()) {
7052 case CK_AtomicToNonAtomic: {
7054 // This does not need to be done in place even for class/array types:
7055 // atomic-to-non-atomic conversion implies copying the object
7057 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7059 return DerivedSuccess(AtomicVal, E);
7063 case CK_UserDefinedConversion:
7064 return StmtVisitorTy::Visit(E->getSubExpr());
7066 case CK_LValueToRValue: {
7068 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7071 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7072 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7075 return DerivedSuccess(RVal, E);
7077 case CK_LValueToRValueBitCast: {
7078 APValue DestValue, SourceValue;
7079 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7081 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7083 return DerivedSuccess(DestValue, E);
7090 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7091 return VisitUnaryPostIncDec(UO);
7093 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7094 return VisitUnaryPostIncDec(UO);
7096 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7097 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7101 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7104 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7105 UO->isIncrementOp(), &RVal))
7107 return DerivedSuccess(RVal, UO);
7110 bool VisitStmtExpr(const StmtExpr *E) {
7111 // We will have checked the full-expressions inside the statement expression
7112 // when they were completed, and don't need to check them again now.
7113 if (Info.checkingForUndefinedBehavior())
7116 const CompoundStmt *CS = E->getSubStmt();
7117 if (CS->body_empty())
7120 BlockScopeRAII Scope(Info);
7121 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7122 BE = CS->body_end();
7125 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7127 Info.FFDiag((*BI)->getBeginLoc(),
7128 diag::note_constexpr_stmt_expr_unsupported);
7131 return this->Visit(FinalExpr) && Scope.destroy();
7134 APValue ReturnValue;
7135 StmtResult Result = { ReturnValue, nullptr };
7136 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7137 if (ESR != ESR_Succeeded) {
7138 // FIXME: If the statement-expression terminated due to 'return',
7139 // 'break', or 'continue', it would be nice to propagate that to
7140 // the outer statement evaluation rather than bailing out.
7141 if (ESR != ESR_Failed)
7142 Info.FFDiag((*BI)->getBeginLoc(),
7143 diag::note_constexpr_stmt_expr_unsupported);
7148 llvm_unreachable("Return from function from the loop above.");
7151 /// Visit a value which is evaluated, but whose value is ignored.
7152 void VisitIgnoredValue(const Expr *E) {
7153 EvaluateIgnoredValue(Info, E);
7156 /// Potentially visit a MemberExpr's base expression.
7157 void VisitIgnoredBaseExpression(const Expr *E) {
7158 // While MSVC doesn't evaluate the base expression, it does diagnose the
7159 // presence of side-effecting behavior.
7160 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7162 VisitIgnoredValue(E);
7168 //===----------------------------------------------------------------------===//
7169 // Common base class for lvalue and temporary evaluation.
7170 //===----------------------------------------------------------------------===//
7172 template<class Derived>
7173 class LValueExprEvaluatorBase
7174 : public ExprEvaluatorBase<Derived> {
7178 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7179 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7181 bool Success(APValue::LValueBase B) {
7186 bool evaluatePointer(const Expr *E, LValue &Result) {
7187 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7191 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7192 : ExprEvaluatorBaseTy(Info), Result(Result),
7193 InvalidBaseOK(InvalidBaseOK) {}
7195 bool Success(const APValue &V, const Expr *E) {
7196 Result.setFrom(this->Info.Ctx, V);
7200 bool VisitMemberExpr(const MemberExpr *E) {
7201 // Handle non-static data members.
7205 EvalOK = evaluatePointer(E->getBase(), Result);
7206 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7207 } else if (E->getBase()->isRValue()) {
7208 assert(E->getBase()->getType()->isRecordType());
7209 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7210 BaseTy = E->getBase()->getType();
7212 EvalOK = this->Visit(E->getBase());
7213 BaseTy = E->getBase()->getType();
7218 Result.setInvalid(E);
7222 const ValueDecl *MD = E->getMemberDecl();
7223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7224 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7225 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7227 if (!HandleLValueMember(this->Info, E, Result, FD))
7229 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7230 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7233 return this->Error(E);
7235 if (MD->getType()->isReferenceType()) {
7237 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7240 return Success(RefValue, E);
7245 bool VisitBinaryOperator(const BinaryOperator *E) {
7246 switch (E->getOpcode()) {
7248 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7252 return HandleMemberPointerAccess(this->Info, E, Result);
7256 bool VisitCastExpr(const CastExpr *E) {
7257 switch (E->getCastKind()) {
7259 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7261 case CK_DerivedToBase:
7262 case CK_UncheckedDerivedToBase:
7263 if (!this->Visit(E->getSubExpr()))
7266 // Now figure out the necessary offset to add to the base LV to get from
7267 // the derived class to the base class.
7268 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7275 //===----------------------------------------------------------------------===//
7276 // LValue Evaluation
7278 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7279 // function designators (in C), decl references to void objects (in C), and
7280 // temporaries (if building with -Wno-address-of-temporary).
7282 // LValue evaluation produces values comprising a base expression of one of the
7288 // * CompoundLiteralExpr in C (and in global scope in C++)
7291 // * ObjCStringLiteralExpr
7295 // * CallExpr for a MakeStringConstant builtin
7296 // - typeid(T) expressions, as TypeInfoLValues
7297 // - Locals and temporaries
7298 // * MaterializeTemporaryExpr
7299 // * Any Expr, with a CallIndex indicating the function in which the temporary
7300 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
7301 // from the AST (FIXME).
7302 // * A MaterializeTemporaryExpr that has static storage duration, with no
7303 // CallIndex, for a lifetime-extended temporary.
7304 // plus an offset in bytes.
7305 //===----------------------------------------------------------------------===//
7307 class LValueExprEvaluator
7308 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7310 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7311 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7313 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7314 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7316 bool VisitDeclRefExpr(const DeclRefExpr *E);
7317 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7318 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7319 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7320 bool VisitMemberExpr(const MemberExpr *E);
7321 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7322 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7323 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7324 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7325 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7326 bool VisitUnaryDeref(const UnaryOperator *E);
7327 bool VisitUnaryReal(const UnaryOperator *E);
7328 bool VisitUnaryImag(const UnaryOperator *E);
7329 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7330 return VisitUnaryPreIncDec(UO);
7332 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7333 return VisitUnaryPreIncDec(UO);
7335 bool VisitBinAssign(const BinaryOperator *BO);
7336 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7338 bool VisitCastExpr(const CastExpr *E) {
7339 switch (E->getCastKind()) {
7341 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7343 case CK_LValueBitCast:
7344 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7345 if (!Visit(E->getSubExpr()))
7347 Result.Designator.setInvalid();
7350 case CK_BaseToDerived:
7351 if (!Visit(E->getSubExpr()))
7353 return HandleBaseToDerivedCast(Info, E, Result);
7356 if (!Visit(E->getSubExpr()))
7358 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7362 } // end anonymous namespace
7364 /// Evaluate an expression as an lvalue. This can be legitimately called on
7365 /// expressions which are not glvalues, in three cases:
7366 /// * function designators in C, and
7367 /// * "extern void" objects
7368 /// * @selector() expressions in Objective-C
7369 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7370 bool InvalidBaseOK) {
7371 assert(E->isGLValue() || E->getType()->isFunctionType() ||
7372 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7373 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7376 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7377 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7379 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7380 return VisitVarDecl(E, VD);
7381 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7382 return Visit(BD->getBinding());
7387 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7389 // If we are within a lambda's call operator, check whether the 'VD' referred
7390 // to within 'E' actually represents a lambda-capture that maps to a
7391 // data-member/field within the closure object, and if so, evaluate to the
7392 // field or what the field refers to.
7393 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7394 isa<DeclRefExpr>(E) &&
7395 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7396 // We don't always have a complete capture-map when checking or inferring if
7397 // the function call operator meets the requirements of a constexpr function
7398 // - but we don't need to evaluate the captures to determine constexprness
7399 // (dcl.constexpr C++17).
7400 if (Info.checkingPotentialConstantExpression())
7403 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7404 // Start with 'Result' referring to the complete closure object...
7405 Result = *Info.CurrentCall->This;
7406 // ... then update it to refer to the field of the closure object
7407 // that represents the capture.
7408 if (!HandleLValueMember(Info, E, Result, FD))
7410 // And if the field is of reference type, update 'Result' to refer to what
7411 // the field refers to.
7412 if (FD->getType()->isReferenceType()) {
7414 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7417 Result.setFrom(Info.Ctx, RVal);
7422 CallStackFrame *Frame = nullptr;
7423 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7424 // Only if a local variable was declared in the function currently being
7425 // evaluated, do we expect to be able to find its value in the current
7426 // frame. (Otherwise it was likely declared in an enclosing context and
7427 // could either have a valid evaluatable value (for e.g. a constexpr
7428 // variable) or be ill-formed (and trigger an appropriate evaluation
7430 if (Info.CurrentCall->Callee &&
7431 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7432 Frame = Info.CurrentCall;
7436 if (!VD->getType()->isReferenceType()) {
7438 Result.set({VD, Frame->Index,
7439 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7446 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7448 if (!V->hasValue()) {
7449 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7450 // adjust the diagnostic to say that.
7451 if (!Info.checkingPotentialConstantExpression())
7452 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7455 return Success(*V, E);
7458 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7459 const MaterializeTemporaryExpr *E) {
7460 // Walk through the expression to find the materialized temporary itself.
7461 SmallVector<const Expr *, 2> CommaLHSs;
7462 SmallVector<SubobjectAdjustment, 2> Adjustments;
7463 const Expr *Inner = E->GetTemporaryExpr()->
7464 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7466 // If we passed any comma operators, evaluate their LHSs.
7467 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7468 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7471 // A materialized temporary with static storage duration can appear within the
7472 // result of a constant expression evaluation, so we need to preserve its
7473 // value for use outside this evaluation.
7475 if (E->getStorageDuration() == SD_Static) {
7476 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
7480 Value = &Info.CurrentCall->createTemporary(
7481 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7484 QualType Type = Inner->getType();
7486 // Materialize the temporary itself.
7487 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7492 // Adjust our lvalue to refer to the desired subobject.
7493 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7495 switch (Adjustments[I].Kind) {
7496 case SubobjectAdjustment::DerivedToBaseAdjustment:
7497 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7500 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7503 case SubobjectAdjustment::FieldAdjustment:
7504 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7506 Type = Adjustments[I].Field->getType();
7509 case SubobjectAdjustment::MemberPointerAdjustment:
7510 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7511 Adjustments[I].Ptr.RHS))
7513 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7522 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7523 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7524 "lvalue compound literal in c++?");
7525 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7526 // only see this when folding in C, so there's no standard to follow here.
7530 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7531 TypeInfoLValue TypeInfo;
7533 if (!E->isPotentiallyEvaluated()) {
7534 if (E->isTypeOperand())
7535 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7537 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7539 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7540 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7541 << E->getExprOperand()->getType()
7542 << E->getExprOperand()->getSourceRange();
7545 if (!Visit(E->getExprOperand()))
7548 Optional<DynamicType> DynType =
7549 ComputeDynamicType(Info, E, Result, AK_TypeId);
7554 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7557 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7560 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7564 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7565 // Handle static data members.
7566 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7567 VisitIgnoredBaseExpression(E->getBase());
7568 return VisitVarDecl(E, VD);
7571 // Handle static member functions.
7572 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7573 if (MD->isStatic()) {
7574 VisitIgnoredBaseExpression(E->getBase());
7579 // Handle non-static data members.
7580 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7583 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7584 // FIXME: Deal with vectors as array subscript bases.
7585 if (E->getBase()->getType()->isVectorType())
7588 bool Success = true;
7589 if (!evaluatePointer(E->getBase(), Result)) {
7590 if (!Info.noteFailure())
7596 if (!EvaluateInteger(E->getIdx(), Index, Info))
7600 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7603 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7604 return evaluatePointer(E->getSubExpr(), Result);
7607 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7608 if (!Visit(E->getSubExpr()))
7610 // __real is a no-op on scalar lvalues.
7611 if (E->getSubExpr()->getType()->isAnyComplexType())
7612 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7616 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7617 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7618 "lvalue __imag__ on scalar?");
7619 if (!Visit(E->getSubExpr()))
7621 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7625 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7626 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7629 if (!this->Visit(UO->getSubExpr()))
7632 return handleIncDec(
7633 this->Info, UO, Result, UO->getSubExpr()->getType(),
7634 UO->isIncrementOp(), nullptr);
7637 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7638 const CompoundAssignOperator *CAO) {
7639 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7644 // The overall lvalue result is the result of evaluating the LHS.
7645 if (!this->Visit(CAO->getLHS())) {
7646 if (Info.noteFailure())
7647 Evaluate(RHS, this->Info, CAO->getRHS());
7651 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7654 return handleCompoundAssignment(
7656 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7657 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7660 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7661 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7666 if (!this->Visit(E->getLHS())) {
7667 if (Info.noteFailure())
7668 Evaluate(NewVal, this->Info, E->getRHS());
7672 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7675 if (Info.getLangOpts().CPlusPlus2a &&
7676 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7679 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7683 //===----------------------------------------------------------------------===//
7684 // Pointer Evaluation
7685 //===----------------------------------------------------------------------===//
7687 /// Attempts to compute the number of bytes available at the pointer
7688 /// returned by a function with the alloc_size attribute. Returns true if we
7689 /// were successful. Places an unsigned number into `Result`.
7691 /// This expects the given CallExpr to be a call to a function with an
7692 /// alloc_size attribute.
7693 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7694 const CallExpr *Call,
7695 llvm::APInt &Result) {
7696 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7698 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7699 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7700 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7701 if (Call->getNumArgs() <= SizeArgNo)
7704 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7705 Expr::EvalResult ExprResult;
7706 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7708 Into = ExprResult.Val.getInt();
7709 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7711 Into = Into.zextOrSelf(BitsInSizeT);
7716 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7719 if (!AllocSize->getNumElemsParam().isValid()) {
7720 Result = std::move(SizeOfElem);
7724 APSInt NumberOfElems;
7725 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7726 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7730 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7734 Result = std::move(BytesAvailable);
7738 /// Convenience function. LVal's base must be a call to an alloc_size
7740 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7742 llvm::APInt &Result) {
7743 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7744 "Can't get the size of a non alloc_size function");
7745 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7746 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7747 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7750 /// Attempts to evaluate the given LValueBase as the result of a call to
7751 /// a function with the alloc_size attribute. If it was possible to do so, this
7752 /// function will return true, make Result's Base point to said function call,
7753 /// and mark Result's Base as invalid.
7754 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7759 // Because we do no form of static analysis, we only support const variables.
7761 // Additionally, we can't support parameters, nor can we support static
7762 // variables (in the latter case, use-before-assign isn't UB; in the former,
7763 // we have no clue what they'll be assigned to).
7765 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7766 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7769 const Expr *Init = VD->getAnyInitializer();
7773 const Expr *E = Init->IgnoreParens();
7774 if (!tryUnwrapAllocSizeCall(E))
7777 // Store E instead of E unwrapped so that the type of the LValue's base is
7778 // what the user wanted.
7779 Result.setInvalid(E);
7781 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7782 Result.addUnsizedArray(Info, E, Pointee);
7787 class PointerExprEvaluator
7788 : public ExprEvaluatorBase<PointerExprEvaluator> {
7792 bool Success(const Expr *E) {
7797 bool evaluateLValue(const Expr *E, LValue &Result) {
7798 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7801 bool evaluatePointer(const Expr *E, LValue &Result) {
7802 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7805 bool visitNonBuiltinCallExpr(const CallExpr *E);
7808 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7809 : ExprEvaluatorBaseTy(info), Result(Result),
7810 InvalidBaseOK(InvalidBaseOK) {}
7812 bool Success(const APValue &V, const Expr *E) {
7813 Result.setFrom(Info.Ctx, V);
7816 bool ZeroInitialization(const Expr *E) {
7817 Result.setNull(Info.Ctx, E->getType());
7821 bool VisitBinaryOperator(const BinaryOperator *E);
7822 bool VisitCastExpr(const CastExpr* E);
7823 bool VisitUnaryAddrOf(const UnaryOperator *E);
7824 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7825 { return Success(E); }
7826 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7827 if (E->isExpressibleAsConstantInitializer())
7829 if (Info.noteFailure())
7830 EvaluateIgnoredValue(Info, E->getSubExpr());
7833 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7834 { return Success(E); }
7835 bool VisitCallExpr(const CallExpr *E);
7836 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7837 bool VisitBlockExpr(const BlockExpr *E) {
7838 if (!E->getBlockDecl()->hasCaptures())
7842 bool VisitCXXThisExpr(const CXXThisExpr *E) {
7843 // Can't look at 'this' when checking a potential constant expression.
7844 if (Info.checkingPotentialConstantExpression())
7846 if (!Info.CurrentCall->This) {
7847 if (Info.getLangOpts().CPlusPlus11)
7848 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7853 Result = *Info.CurrentCall->This;
7854 // If we are inside a lambda's call operator, the 'this' expression refers
7855 // to the enclosing '*this' object (either by value or reference) which is
7856 // either copied into the closure object's field that represents the '*this'
7857 // or refers to '*this'.
7858 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7859 // Update 'Result' to refer to the data member/field of the closure object
7860 // that represents the '*this' capture.
7861 if (!HandleLValueMember(Info, E, Result,
7862 Info.CurrentCall->LambdaThisCaptureField))
7864 // If we captured '*this' by reference, replace the field with its referent.
7865 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7866 ->isPointerType()) {
7868 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7872 Result.setFrom(Info.Ctx, RVal);
7878 bool VisitCXXNewExpr(const CXXNewExpr *E);
7880 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7881 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7882 APValue LValResult = E->EvaluateInContext(
7883 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7884 Result.setFrom(Info.Ctx, LValResult);
7888 // FIXME: Missing: @protocol, @selector
7890 } // end anonymous namespace
7892 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7893 bool InvalidBaseOK) {
7894 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7895 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7898 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7899 if (E->getOpcode() != BO_Add &&
7900 E->getOpcode() != BO_Sub)
7901 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7903 const Expr *PExp = E->getLHS();
7904 const Expr *IExp = E->getRHS();
7905 if (IExp->getType()->isPointerType())
7906 std::swap(PExp, IExp);
7908 bool EvalPtrOK = evaluatePointer(PExp, Result);
7909 if (!EvalPtrOK && !Info.noteFailure())
7912 llvm::APSInt Offset;
7913 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7916 if (E->getOpcode() == BO_Sub)
7917 negateAsSigned(Offset);
7919 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7920 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7923 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7924 return evaluateLValue(E->getSubExpr(), Result);
7927 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7928 const Expr *SubExpr = E->getSubExpr();
7930 switch (E->getCastKind()) {
7934 case CK_CPointerToObjCPointerCast:
7935 case CK_BlockPointerToObjCPointerCast:
7936 case CK_AnyPointerToBlockPointerCast:
7937 case CK_AddressSpaceConversion:
7938 if (!Visit(SubExpr))
7940 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7941 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7942 // also static_casts, but we disallow them as a resolution to DR1312.
7943 if (!E->getType()->isVoidPointerType()) {
7944 if (!Result.InvalidBase && !Result.Designator.Invalid &&
7945 !Result.IsNullPtr &&
7946 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
7947 E->getType()->getPointeeType()) &&
7948 Info.getStdAllocatorCaller("allocate")) {
7949 // Inside a call to std::allocator::allocate and friends, we permit
7950 // casting from void* back to cv1 T* for a pointer that points to a
7953 Result.Designator.setInvalid();
7954 if (SubExpr->getType()->isVoidPointerType())
7955 CCEDiag(E, diag::note_constexpr_invalid_cast)
7956 << 3 << SubExpr->getType();
7958 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7961 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7962 ZeroInitialization(E);
7965 case CK_DerivedToBase:
7966 case CK_UncheckedDerivedToBase:
7967 if (!evaluatePointer(E->getSubExpr(), Result))
7969 if (!Result.Base && Result.Offset.isZero())
7972 // Now figure out the necessary offset to add to the base LV to get from
7973 // the derived class to the base class.
7974 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7975 castAs<PointerType>()->getPointeeType(),
7978 case CK_BaseToDerived:
7979 if (!Visit(E->getSubExpr()))
7981 if (!Result.Base && Result.Offset.isZero())
7983 return HandleBaseToDerivedCast(Info, E, Result);
7986 if (!Visit(E->getSubExpr()))
7988 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7990 case CK_NullToPointer:
7991 VisitIgnoredValue(E->getSubExpr());
7992 return ZeroInitialization(E);
7994 case CK_IntegralToPointer: {
7995 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7998 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8001 if (Value.isInt()) {
8002 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8003 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8004 Result.Base = (Expr*)nullptr;
8005 Result.InvalidBase = false;
8006 Result.Offset = CharUnits::fromQuantity(N);
8007 Result.Designator.setInvalid();
8008 Result.IsNullPtr = false;
8011 // Cast is of an lvalue, no need to change value.
8012 Result.setFrom(Info.Ctx, Value);
8017 case CK_ArrayToPointerDecay: {
8018 if (SubExpr->isGLValue()) {
8019 if (!evaluateLValue(SubExpr, Result))
8022 APValue &Value = Info.CurrentCall->createTemporary(
8023 SubExpr, SubExpr->getType(), false, Result);
8024 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8027 // The result is a pointer to the first element of the array.
8028 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8029 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8030 Result.addArray(Info, E, CAT);
8032 Result.addUnsizedArray(Info, E, AT->getElementType());
8036 case CK_FunctionToPointerDecay:
8037 return evaluateLValue(SubExpr, Result);
8039 case CK_LValueToRValue: {
8041 if (!evaluateLValue(E->getSubExpr(), LVal))
8045 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8046 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8048 return InvalidBaseOK &&
8049 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8050 return Success(RVal, E);
8054 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8057 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8058 UnaryExprOrTypeTrait ExprKind) {
8059 // C++ [expr.alignof]p3:
8060 // When alignof is applied to a reference type, the result is the
8061 // alignment of the referenced type.
8062 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8063 T = Ref->getPointeeType();
8065 if (T.getQualifiers().hasUnaligned())
8066 return CharUnits::One();
8068 const bool AlignOfReturnsPreferred =
8069 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8071 // __alignof is defined to return the preferred alignment.
8072 // Before 8, clang returned the preferred alignment for alignof and _Alignof
8074 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8075 return Info.Ctx.toCharUnitsFromBits(
8076 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8077 // alignof and _Alignof are defined to return the ABI alignment.
8078 else if (ExprKind == UETT_AlignOf)
8079 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8081 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8084 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8085 UnaryExprOrTypeTrait ExprKind) {
8086 E = E->IgnoreParens();
8088 // The kinds of expressions that we have special-case logic here for
8089 // should be kept up to date with the special checks for those
8090 // expressions in Sema.
8092 // alignof decl is always accepted, even if it doesn't make sense: we default
8093 // to 1 in those cases.
8094 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8095 return Info.Ctx.getDeclAlign(DRE->getDecl(),
8096 /*RefAsPointee*/true);
8098 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8099 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8100 /*RefAsPointee*/true);
8102 return GetAlignOfType(Info, E->getType(), ExprKind);
8105 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8106 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8107 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8110 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8113 Result.setInvalid(E);
8114 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8115 Result.addUnsizedArray(Info, E, PointeeTy);
8119 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8120 if (IsStringLiteralCall(E))
8123 if (unsigned BuiltinOp = E->getBuiltinCallee())
8124 return VisitBuiltinCallExpr(E, BuiltinOp);
8126 return visitNonBuiltinCallExpr(E);
8129 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8130 unsigned BuiltinOp) {
8131 switch (BuiltinOp) {
8132 case Builtin::BI__builtin_addressof:
8133 return evaluateLValue(E->getArg(0), Result);
8134 case Builtin::BI__builtin_assume_aligned: {
8135 // We need to be very careful here because: if the pointer does not have the
8136 // asserted alignment, then the behavior is undefined, and undefined
8137 // behavior is non-constant.
8138 if (!evaluatePointer(E->getArg(0), Result))
8141 LValue OffsetResult(Result);
8143 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
8145 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8147 if (E->getNumArgs() > 2) {
8149 if (!EvaluateInteger(E->getArg(2), Offset, Info))
8152 int64_t AdditionalOffset = -Offset.getZExtValue();
8153 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8156 // If there is a base object, then it must have the correct alignment.
8157 if (OffsetResult.Base) {
8158 CharUnits BaseAlignment;
8159 if (const ValueDecl *VD =
8160 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
8161 BaseAlignment = Info.Ctx.getDeclAlign(VD);
8162 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
8163 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
8165 BaseAlignment = GetAlignOfType(
8166 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
8169 if (BaseAlignment < Align) {
8170 Result.Designator.setInvalid();
8171 // FIXME: Add support to Diagnostic for long / long long.
8172 CCEDiag(E->getArg(0),
8173 diag::note_constexpr_baa_insufficient_alignment) << 0
8174 << (unsigned)BaseAlignment.getQuantity()
8175 << (unsigned)Align.getQuantity();
8180 // The offset must also have the correct alignment.
8181 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8182 Result.Designator.setInvalid();
8185 ? CCEDiag(E->getArg(0),
8186 diag::note_constexpr_baa_insufficient_alignment) << 1
8187 : CCEDiag(E->getArg(0),
8188 diag::note_constexpr_baa_value_insufficient_alignment))
8189 << (int)OffsetResult.Offset.getQuantity()
8190 << (unsigned)Align.getQuantity();
8196 case Builtin::BI__builtin_operator_new:
8197 return HandleOperatorNewCall(Info, E, Result);
8198 case Builtin::BI__builtin_launder:
8199 return evaluatePointer(E->getArg(0), Result);
8200 case Builtin::BIstrchr:
8201 case Builtin::BIwcschr:
8202 case Builtin::BImemchr:
8203 case Builtin::BIwmemchr:
8204 if (Info.getLangOpts().CPlusPlus11)
8205 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8206 << /*isConstexpr*/0 << /*isConstructor*/0
8207 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8209 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8211 case Builtin::BI__builtin_strchr:
8212 case Builtin::BI__builtin_wcschr:
8213 case Builtin::BI__builtin_memchr:
8214 case Builtin::BI__builtin_char_memchr:
8215 case Builtin::BI__builtin_wmemchr: {
8216 if (!Visit(E->getArg(0)))
8219 if (!EvaluateInteger(E->getArg(1), Desired, Info))
8221 uint64_t MaxLength = uint64_t(-1);
8222 if (BuiltinOp != Builtin::BIstrchr &&
8223 BuiltinOp != Builtin::BIwcschr &&
8224 BuiltinOp != Builtin::BI__builtin_strchr &&
8225 BuiltinOp != Builtin::BI__builtin_wcschr) {
8227 if (!EvaluateInteger(E->getArg(2), N, Info))
8229 MaxLength = N.getExtValue();
8231 // We cannot find the value if there are no candidates to match against.
8232 if (MaxLength == 0u)
8233 return ZeroInitialization(E);
8234 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8235 Result.Designator.Invalid)
8237 QualType CharTy = Result.Designator.getType(Info.Ctx);
8238 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8239 BuiltinOp == Builtin::BI__builtin_memchr;
8241 Info.Ctx.hasSameUnqualifiedType(
8242 CharTy, E->getArg(0)->getType()->getPointeeType()));
8243 // Pointers to const void may point to objects of incomplete type.
8244 if (IsRawByte && CharTy->isIncompleteType()) {
8245 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8248 // Give up on byte-oriented matching against multibyte elements.
8249 // FIXME: We can compare the bytes in the correct order.
8250 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8252 // Figure out what value we're actually looking for (after converting to
8253 // the corresponding unsigned type if necessary).
8254 uint64_t DesiredVal;
8255 bool StopAtNull = false;
8256 switch (BuiltinOp) {
8257 case Builtin::BIstrchr:
8258 case Builtin::BI__builtin_strchr:
8259 // strchr compares directly to the passed integer, and therefore
8260 // always fails if given an int that is not a char.
8261 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8262 E->getArg(1)->getType(),
8265 return ZeroInitialization(E);
8268 case Builtin::BImemchr:
8269 case Builtin::BI__builtin_memchr:
8270 case Builtin::BI__builtin_char_memchr:
8271 // memchr compares by converting both sides to unsigned char. That's also
8272 // correct for strchr if we get this far (to cope with plain char being
8273 // unsigned in the strchr case).
8274 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8277 case Builtin::BIwcschr:
8278 case Builtin::BI__builtin_wcschr:
8281 case Builtin::BIwmemchr:
8282 case Builtin::BI__builtin_wmemchr:
8283 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8284 DesiredVal = Desired.getZExtValue();
8288 for (; MaxLength; --MaxLength) {
8290 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8293 if (Char.getInt().getZExtValue() == DesiredVal)
8295 if (StopAtNull && !Char.getInt())
8297 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8300 // Not found: return nullptr.
8301 return ZeroInitialization(E);
8304 case Builtin::BImemcpy:
8305 case Builtin::BImemmove:
8306 case Builtin::BIwmemcpy:
8307 case Builtin::BIwmemmove:
8308 if (Info.getLangOpts().CPlusPlus11)
8309 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8310 << /*isConstexpr*/0 << /*isConstructor*/0
8311 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8313 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8315 case Builtin::BI__builtin_memcpy:
8316 case Builtin::BI__builtin_memmove:
8317 case Builtin::BI__builtin_wmemcpy:
8318 case Builtin::BI__builtin_wmemmove: {
8319 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8320 BuiltinOp == Builtin::BIwmemmove ||
8321 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8322 BuiltinOp == Builtin::BI__builtin_wmemmove;
8323 bool Move = BuiltinOp == Builtin::BImemmove ||
8324 BuiltinOp == Builtin::BIwmemmove ||
8325 BuiltinOp == Builtin::BI__builtin_memmove ||
8326 BuiltinOp == Builtin::BI__builtin_wmemmove;
8328 // The result of mem* is the first argument.
8329 if (!Visit(E->getArg(0)))
8331 LValue Dest = Result;
8334 if (!EvaluatePointer(E->getArg(1), Src, Info))
8338 if (!EvaluateInteger(E->getArg(2), N, Info))
8340 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8342 // If the size is zero, we treat this as always being a valid no-op.
8343 // (Even if one of the src and dest pointers is null.)
8347 // Otherwise, if either of the operands is null, we can't proceed. Don't
8348 // try to determine the type of the copied objects, because there aren't
8350 if (!Src.Base || !Dest.Base) {
8352 (!Src.Base ? Src : Dest).moveInto(Val);
8353 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8354 << Move << WChar << !!Src.Base
8355 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8358 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8361 // We require that Src and Dest are both pointers to arrays of
8362 // trivially-copyable type. (For the wide version, the designator will be
8363 // invalid if the designated object is not a wchar_t.)
8364 QualType T = Dest.Designator.getType(Info.Ctx);
8365 QualType SrcT = Src.Designator.getType(Info.Ctx);
8366 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8367 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8370 if (T->isIncompleteType()) {
8371 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8374 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8375 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8379 // Figure out how many T's we're copying.
8380 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8383 llvm::APInt OrigN = N;
8384 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8386 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8387 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8393 // Check that the copying will remain within the arrays, just so that we
8394 // can give a more meaningful diagnostic. This implicitly also checks that
8395 // N fits into 64 bits.
8396 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8397 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8398 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8399 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8400 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8401 << N.toString(10, /*Signed*/false);
8404 uint64_t NElems = N.getZExtValue();
8405 uint64_t NBytes = NElems * TSize;
8407 // Check for overlap.
8409 if (HasSameBase(Src, Dest)) {
8410 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8411 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8412 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8413 // Dest is inside the source region.
8415 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8418 // For memmove and friends, copy backwards.
8419 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8420 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8423 } else if (!Move && SrcOffset >= DestOffset &&
8424 SrcOffset - DestOffset < NBytes) {
8425 // Src is inside the destination region for memcpy: invalid.
8426 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8433 // FIXME: Set WantObjectRepresentation to true if we're copying a
8435 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8436 !handleAssignment(Info, E, Dest, T, Val))
8438 // Do not iterate past the last element; if we're copying backwards, that
8439 // might take us off the start of the array.
8442 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8443 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8452 return visitNonBuiltinCallExpr(E);
8455 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8456 APValue &Result, const InitListExpr *ILE,
8457 QualType AllocType);
8459 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8460 if (!Info.getLangOpts().CPlusPlus2a)
8461 Info.CCEDiag(E, diag::note_constexpr_new);
8463 // We cannot speculatively evaluate a delete expression.
8464 if (Info.SpeculativeEvaluationDepth)
8467 FunctionDecl *OperatorNew = E->getOperatorNew();
8469 bool IsNothrow = false;
8470 bool IsPlacement = false;
8471 if (OperatorNew->isReservedGlobalPlacementOperator() &&
8472 Info.CurrentCall->isStdFunction() && !E->isArray()) {
8473 // FIXME Support array placement new.
8474 assert(E->getNumPlacementArgs() == 1);
8475 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8477 if (Result.Designator.Invalid)
8480 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8481 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8482 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8484 } else if (E->getNumPlacementArgs()) {
8485 // The only new-placement list we support is of the form (std::nothrow).
8487 // FIXME: There is no restriction on this, but it's not clear that any
8488 // other form makes any sense. We get here for cases such as:
8490 // new (std::align_val_t{N}) X(int)
8492 // (which should presumably be valid only if N is a multiple of
8493 // alignof(int), and in any case can't be deallocated unless N is
8494 // alignof(X) and X has new-extended alignment).
8495 if (E->getNumPlacementArgs() != 1 ||
8496 !E->getPlacementArg(0)->getType()->isNothrowT())
8497 return Error(E, diag::note_constexpr_new_placement);
8500 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8505 const Expr *Init = E->getInitializer();
8506 const InitListExpr *ResizedArrayILE = nullptr;
8508 QualType AllocType = E->getAllocatedType();
8509 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8510 const Expr *Stripped = *ArraySize;
8511 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8512 Stripped = ICE->getSubExpr())
8513 if (ICE->getCastKind() != CK_NoOp &&
8514 ICE->getCastKind() != CK_IntegralCast)
8517 llvm::APSInt ArrayBound;
8518 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8521 // C++ [expr.new]p9:
8522 // The expression is erroneous if:
8523 // -- [...] its value before converting to size_t [or] applying the
8524 // second standard conversion sequence is less than zero
8525 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8527 return ZeroInitialization(E);
8529 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8530 << ArrayBound << (*ArraySize)->getSourceRange();
8534 // -- its value is such that the size of the allocated object would
8535 // exceed the implementation-defined limit
8536 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8538 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8540 return ZeroInitialization(E);
8542 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8543 << ArrayBound << (*ArraySize)->getSourceRange();
8547 // -- the new-initializer is a braced-init-list and the number of
8548 // array elements for which initializers are provided [...]
8549 // exceeds the number of elements to initialize
8551 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8552 assert(CAT && "unexpected type for array initializer");
8555 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8556 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8557 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8558 if (InitBound.ugt(AllocBound)) {
8560 return ZeroInitialization(E);
8562 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8563 << AllocBound.toString(10, /*Signed=*/false)
8564 << InitBound.toString(10, /*Signed=*/false)
8565 << (*ArraySize)->getSourceRange();
8569 // If the sizes differ, we must have an initializer list, and we need
8570 // special handling for this case when we initialize.
8571 if (InitBound != AllocBound)
8572 ResizedArrayILE = cast<InitListExpr>(Init);
8575 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8576 ArrayType::Normal, 0);
8578 assert(!AllocType->isArrayType() &&
8579 "array allocation with non-array new");
8584 AccessKinds AK = AK_Construct;
8585 struct FindObjectHandler {
8589 const AccessKinds AccessKind;
8592 typedef bool result_type;
8593 bool failed() { return false; }
8594 bool found(APValue &Subobj, QualType SubobjType) {
8595 // FIXME: Reject the cases where [basic.life]p8 would not permit the
8596 // old name of the object to be used to name the new object.
8597 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8598 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8599 SubobjType << AllocType;
8605 bool found(APSInt &Value, QualType SubobjType) {
8606 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8609 bool found(APFloat &Value, QualType SubobjType) {
8610 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8613 } Handler = {Info, E, AllocType, AK, nullptr};
8615 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8616 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8619 Val = Handler.Value;
8622 // The lifetime of an object o of type T ends when [...] the storage
8623 // which the object occupies is [...] reused by an object that is not
8624 // nested within o (6.6.2).
8627 // Perform the allocation and obtain a pointer to the resulting object.
8628 Val = Info.createHeapAlloc(E, AllocType, Result);
8633 if (ResizedArrayILE) {
8634 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8638 if (!EvaluateInPlace(*Val, Info, Result, Init))
8641 *Val = getDefaultInitValue(AllocType);
8644 // Array new returns a pointer to the first element, not a pointer to the
8646 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8647 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8651 //===----------------------------------------------------------------------===//
8652 // Member Pointer Evaluation
8653 //===----------------------------------------------------------------------===//
8656 class MemberPointerExprEvaluator
8657 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8660 bool Success(const ValueDecl *D) {
8661 Result = MemberPtr(D);
8666 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8667 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8669 bool Success(const APValue &V, const Expr *E) {
8673 bool ZeroInitialization(const Expr *E) {
8674 return Success((const ValueDecl*)nullptr);
8677 bool VisitCastExpr(const CastExpr *E);
8678 bool VisitUnaryAddrOf(const UnaryOperator *E);
8680 } // end anonymous namespace
8682 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8684 assert(E->isRValue() && E->getType()->isMemberPointerType());
8685 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8688 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8689 switch (E->getCastKind()) {
8691 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8693 case CK_NullToMemberPointer:
8694 VisitIgnoredValue(E->getSubExpr());
8695 return ZeroInitialization(E);
8697 case CK_BaseToDerivedMemberPointer: {
8698 if (!Visit(E->getSubExpr()))
8700 if (E->path_empty())
8702 // Base-to-derived member pointer casts store the path in derived-to-base
8703 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8704 // the wrong end of the derived->base arc, so stagger the path by one class.
8705 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8706 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8707 PathI != PathE; ++PathI) {
8708 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8709 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8710 if (!Result.castToDerived(Derived))
8713 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8714 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8719 case CK_DerivedToBaseMemberPointer:
8720 if (!Visit(E->getSubExpr()))
8722 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8723 PathE = E->path_end(); PathI != PathE; ++PathI) {
8724 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8725 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8726 if (!Result.castToBase(Base))
8733 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8734 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8735 // member can be formed.
8736 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8739 //===----------------------------------------------------------------------===//
8740 // Record Evaluation
8741 //===----------------------------------------------------------------------===//
8744 class RecordExprEvaluator
8745 : public ExprEvaluatorBase<RecordExprEvaluator> {
8750 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8751 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8753 bool Success(const APValue &V, const Expr *E) {
8757 bool ZeroInitialization(const Expr *E) {
8758 return ZeroInitialization(E, E->getType());
8760 bool ZeroInitialization(const Expr *E, QualType T);
8762 bool VisitCallExpr(const CallExpr *E) {
8763 return handleCallExpr(E, Result, &This);
8765 bool VisitCastExpr(const CastExpr *E);
8766 bool VisitInitListExpr(const InitListExpr *E);
8767 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8768 return VisitCXXConstructExpr(E, E->getType());
8770 bool VisitLambdaExpr(const LambdaExpr *E);
8771 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
8772 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
8773 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
8774 bool VisitBinCmp(const BinaryOperator *E);
8778 /// Perform zero-initialization on an object of non-union class type.
8779 /// C++11 [dcl.init]p5:
8780 /// To zero-initialize an object or reference of type T means:
8782 /// -- if T is a (possibly cv-qualified) non-union class type,
8783 /// each non-static data member and each base-class subobject is
8784 /// zero-initialized
8785 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8786 const RecordDecl *RD,
8787 const LValue &This, APValue &Result) {
8788 assert(!RD->isUnion() && "Expected non-union class type");
8789 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8790 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
8791 std::distance(RD->field_begin(), RD->field_end()));
8793 if (RD->isInvalidDecl()) return false;
8794 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8798 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
8799 End = CD->bases_end(); I != End; ++I, ++Index) {
8800 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8801 LValue Subobject = This;
8802 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8804 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
8805 Result.getStructBase(Index)))
8810 for (const auto *I : RD->fields()) {
8811 // -- if T is a reference type, no initialization is performed.
8812 if (I->getType()->isReferenceType())
8815 LValue Subobject = This;
8816 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
8819 ImplicitValueInitExpr VIE(I->getType());
8820 if (!EvaluateInPlace(
8821 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
8828 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8829 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
8830 if (RD->isInvalidDecl()) return false;
8831 if (RD->isUnion()) {
8832 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8833 // object's first non-static named data member is zero-initialized
8834 RecordDecl::field_iterator I = RD->field_begin();
8835 if (I == RD->field_end()) {
8836 Result = APValue((const FieldDecl*)nullptr);
8840 LValue Subobject = This;
8841 if (!HandleLValueMember(Info, E, Subobject, *I))
8843 Result = APValue(*I);
8844 ImplicitValueInitExpr VIE(I->getType());
8845 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
8848 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
8849 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
8853 return HandleClassZeroInitialization(Info, E, RD, This, Result);
8856 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8857 switch (E->getCastKind()) {
8859 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8861 case CK_ConstructorConversion:
8862 return Visit(E->getSubExpr());
8864 case CK_DerivedToBase:
8865 case CK_UncheckedDerivedToBase: {
8866 APValue DerivedObject;
8867 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
8869 if (!DerivedObject.isStruct())
8870 return Error(E->getSubExpr());
8872 // Derived-to-base rvalue conversion: just slice off the derived part.
8873 APValue *Value = &DerivedObject;
8874 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8875 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8876 PathE = E->path_end(); PathI != PathE; ++PathI) {
8877 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8878 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8879 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8888 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8889 if (E->isTransparent())
8890 return Visit(E->getInit(0));
8892 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
8893 if (RD->isInvalidDecl()) return false;
8894 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8895 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8897 EvalInfo::EvaluatingConstructorRAII EvalObj(
8899 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8900 CXXRD && CXXRD->getNumBases());
8902 if (RD->isUnion()) {
8903 const FieldDecl *Field = E->getInitializedFieldInUnion();
8904 Result = APValue(Field);
8908 // If the initializer list for a union does not contain any elements, the
8909 // first element of the union is value-initialized.
8910 // FIXME: The element should be initialized from an initializer list.
8911 // Is this difference ever observable for initializer lists which
8913 ImplicitValueInitExpr VIE(Field->getType());
8914 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8916 LValue Subobject = This;
8917 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8920 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8921 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8922 isa<CXXDefaultInitExpr>(InitExpr));
8924 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
8927 if (!Result.hasValue())
8928 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8929 std::distance(RD->field_begin(), RD->field_end()));
8930 unsigned ElementNo = 0;
8931 bool Success = true;
8933 // Initialize base classes.
8934 if (CXXRD && CXXRD->getNumBases()) {
8935 for (const auto &Base : CXXRD->bases()) {
8936 assert(ElementNo < E->getNumInits() && "missing init for base class");
8937 const Expr *Init = E->getInit(ElementNo);
8939 LValue Subobject = This;
8940 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8943 APValue &FieldVal = Result.getStructBase(ElementNo);
8944 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
8945 if (!Info.noteFailure())
8952 EvalObj.finishedConstructingBases();
8955 // Initialize members.
8956 for (const auto *Field : RD->fields()) {
8957 // Anonymous bit-fields are not considered members of the class for
8958 // purposes of aggregate initialization.
8959 if (Field->isUnnamedBitfield())
8962 LValue Subobject = This;
8964 bool HaveInit = ElementNo < E->getNumInits();
8966 // FIXME: Diagnostics here should point to the end of the initializer
8967 // list, not the start.
8968 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
8969 Subobject, Field, &Layout))
8972 // Perform an implicit value-initialization for members beyond the end of
8973 // the initializer list.
8974 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
8975 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
8977 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8978 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8979 isa<CXXDefaultInitExpr>(Init));
8981 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8982 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8983 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
8984 FieldVal, Field))) {
8985 if (!Info.noteFailure())
8994 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8996 // Note that E's type is not necessarily the type of our class here; we might
8997 // be initializing an array element instead.
8998 const CXXConstructorDecl *FD = E->getConstructor();
8999 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9001 bool ZeroInit = E->requiresZeroInitialization();
9002 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9003 // If we've already performed zero-initialization, we're already done.
9004 if (Result.hasValue())
9008 return ZeroInitialization(E, T);
9010 Result = getDefaultInitValue(T);
9014 const FunctionDecl *Definition = nullptr;
9015 auto Body = FD->getBody(Definition);
9017 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9020 // Avoid materializing a temporary for an elidable copy/move constructor.
9021 if (E->isElidable() && !ZeroInit)
9022 if (const MaterializeTemporaryExpr *ME
9023 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9024 return Visit(ME->GetTemporaryExpr());
9026 if (ZeroInit && !ZeroInitialization(E, T))
9029 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9030 return HandleConstructorCall(E, This, Args,
9031 cast<CXXConstructorDecl>(Definition), Info,
9035 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9036 const CXXInheritedCtorInitExpr *E) {
9037 if (!Info.CurrentCall) {
9038 assert(Info.checkingPotentialConstantExpression());
9042 const CXXConstructorDecl *FD = E->getConstructor();
9043 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9046 const FunctionDecl *Definition = nullptr;
9047 auto Body = FD->getBody(Definition);
9049 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9052 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9053 cast<CXXConstructorDecl>(Definition), Info,
9057 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9058 const CXXStdInitializerListExpr *E) {
9059 const ConstantArrayType *ArrayType =
9060 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9063 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9066 // Get a pointer to the first element of the array.
9067 Array.addArray(Info, E, ArrayType);
9069 // FIXME: Perform the checks on the field types in SemaInit.
9070 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9071 RecordDecl::field_iterator Field = Record->field_begin();
9072 if (Field == Record->field_end())
9076 if (!Field->getType()->isPointerType() ||
9077 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9078 ArrayType->getElementType()))
9081 // FIXME: What if the initializer_list type has base classes, etc?
9082 Result = APValue(APValue::UninitStruct(), 0, 2);
9083 Array.moveInto(Result.getStructField(0));
9085 if (++Field == Record->field_end())
9088 if (Field->getType()->isPointerType() &&
9089 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9090 ArrayType->getElementType())) {
9092 if (!HandleLValueArrayAdjustment(Info, E, Array,
9093 ArrayType->getElementType(),
9094 ArrayType->getSize().getZExtValue()))
9096 Array.moveInto(Result.getStructField(1));
9097 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9099 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9103 if (++Field != Record->field_end())
9109 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9110 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9111 if (ClosureClass->isInvalidDecl())
9114 const size_t NumFields =
9115 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9117 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9118 E->capture_init_end()) &&
9119 "The number of lambda capture initializers should equal the number of "
9120 "fields within the closure type");
9122 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9123 // Iterate through all the lambda's closure object's fields and initialize
9125 auto *CaptureInitIt = E->capture_init_begin();
9126 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9127 bool Success = true;
9128 for (const auto *Field : ClosureClass->fields()) {
9129 assert(CaptureInitIt != E->capture_init_end());
9130 // Get the initializer for this field
9131 Expr *const CurFieldInit = *CaptureInitIt++;
9133 // If there is no initializer, either this is a VLA or an error has
9138 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9139 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9140 if (!Info.keepEvaluatingAfterFailure())
9149 static bool EvaluateRecord(const Expr *E, const LValue &This,
9150 APValue &Result, EvalInfo &Info) {
9151 assert(E->isRValue() && E->getType()->isRecordType() &&
9152 "can't evaluate expression as a record rvalue");
9153 return RecordExprEvaluator(Info, This, Result).Visit(E);
9156 //===----------------------------------------------------------------------===//
9157 // Temporary Evaluation
9159 // Temporaries are represented in the AST as rvalues, but generally behave like
9160 // lvalues. The full-object of which the temporary is a subobject is implicitly
9161 // materialized so that a reference can bind to it.
9162 //===----------------------------------------------------------------------===//
9164 class TemporaryExprEvaluator
9165 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9167 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9168 LValueExprEvaluatorBaseTy(Info, Result, false) {}
9170 /// Visit an expression which constructs the value of this temporary.
9171 bool VisitConstructExpr(const Expr *E) {
9173 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9174 return EvaluateInPlace(Value, Info, Result, E);
9177 bool VisitCastExpr(const CastExpr *E) {
9178 switch (E->getCastKind()) {
9180 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9182 case CK_ConstructorConversion:
9183 return VisitConstructExpr(E->getSubExpr());
9186 bool VisitInitListExpr(const InitListExpr *E) {
9187 return VisitConstructExpr(E);
9189 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9190 return VisitConstructExpr(E);
9192 bool VisitCallExpr(const CallExpr *E) {
9193 return VisitConstructExpr(E);
9195 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9196 return VisitConstructExpr(E);
9198 bool VisitLambdaExpr(const LambdaExpr *E) {
9199 return VisitConstructExpr(E);
9202 } // end anonymous namespace
9204 /// Evaluate an expression of record type as a temporary.
9205 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9206 assert(E->isRValue() && E->getType()->isRecordType());
9207 return TemporaryExprEvaluator(Info, Result).Visit(E);
9210 //===----------------------------------------------------------------------===//
9211 // Vector Evaluation
9212 //===----------------------------------------------------------------------===//
9215 class VectorExprEvaluator
9216 : public ExprEvaluatorBase<VectorExprEvaluator> {
9220 VectorExprEvaluator(EvalInfo &info, APValue &Result)
9221 : ExprEvaluatorBaseTy(info), Result(Result) {}
9223 bool Success(ArrayRef<APValue> V, const Expr *E) {
9224 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9225 // FIXME: remove this APValue copy.
9226 Result = APValue(V.data(), V.size());
9229 bool Success(const APValue &V, const Expr *E) {
9230 assert(V.isVector());
9234 bool ZeroInitialization(const Expr *E);
9236 bool VisitUnaryReal(const UnaryOperator *E)
9237 { return Visit(E->getSubExpr()); }
9238 bool VisitCastExpr(const CastExpr* E);
9239 bool VisitInitListExpr(const InitListExpr *E);
9240 bool VisitUnaryImag(const UnaryOperator *E);
9241 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9242 // binary comparisons, binary and/or/xor,
9243 // shufflevector, ExtVectorElementExpr
9245 } // end anonymous namespace
9247 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9248 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9249 return VectorExprEvaluator(Info, Result).Visit(E);
9252 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9253 const VectorType *VTy = E->getType()->castAs<VectorType>();
9254 unsigned NElts = VTy->getNumElements();
9256 const Expr *SE = E->getSubExpr();
9257 QualType SETy = SE->getType();
9259 switch (E->getCastKind()) {
9260 case CK_VectorSplat: {
9261 APValue Val = APValue();
9262 if (SETy->isIntegerType()) {
9264 if (!EvaluateInteger(SE, IntResult, Info))
9266 Val = APValue(std::move(IntResult));
9267 } else if (SETy->isRealFloatingType()) {
9268 APFloat FloatResult(0.0);
9269 if (!EvaluateFloat(SE, FloatResult, Info))
9271 Val = APValue(std::move(FloatResult));
9276 // Splat and create vector APValue.
9277 SmallVector<APValue, 4> Elts(NElts, Val);
9278 return Success(Elts, E);
9281 // Evaluate the operand into an APInt we can extract from.
9282 llvm::APInt SValInt;
9283 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9285 // Extract the elements
9286 QualType EltTy = VTy->getElementType();
9287 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9288 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9289 SmallVector<APValue, 4> Elts;
9290 if (EltTy->isRealFloatingType()) {
9291 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9292 unsigned FloatEltSize = EltSize;
9293 if (&Sem == &APFloat::x87DoubleExtended())
9295 for (unsigned i = 0; i < NElts; i++) {
9298 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9300 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9301 Elts.push_back(APValue(APFloat(Sem, Elt)));
9303 } else if (EltTy->isIntegerType()) {
9304 for (unsigned i = 0; i < NElts; i++) {
9307 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9309 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9310 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9315 return Success(Elts, E);
9318 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9323 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9324 const VectorType *VT = E->getType()->castAs<VectorType>();
9325 unsigned NumInits = E->getNumInits();
9326 unsigned NumElements = VT->getNumElements();
9328 QualType EltTy = VT->getElementType();
9329 SmallVector<APValue, 4> Elements;
9331 // The number of initializers can be less than the number of
9332 // vector elements. For OpenCL, this can be due to nested vector
9333 // initialization. For GCC compatibility, missing trailing elements
9334 // should be initialized with zeroes.
9335 unsigned CountInits = 0, CountElts = 0;
9336 while (CountElts < NumElements) {
9337 // Handle nested vector initialization.
9338 if (CountInits < NumInits
9339 && E->getInit(CountInits)->getType()->isVectorType()) {
9341 if (!EvaluateVector(E->getInit(CountInits), v, Info))
9343 unsigned vlen = v.getVectorLength();
9344 for (unsigned j = 0; j < vlen; j++)
9345 Elements.push_back(v.getVectorElt(j));
9347 } else if (EltTy->isIntegerType()) {
9348 llvm::APSInt sInt(32);
9349 if (CountInits < NumInits) {
9350 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9352 } else // trailing integer zero.
9353 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9354 Elements.push_back(APValue(sInt));
9357 llvm::APFloat f(0.0);
9358 if (CountInits < NumInits) {
9359 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9361 } else // trailing float zero.
9362 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9363 Elements.push_back(APValue(f));
9368 return Success(Elements, E);
9372 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9373 const auto *VT = E->getType()->castAs<VectorType>();
9374 QualType EltTy = VT->getElementType();
9375 APValue ZeroElement;
9376 if (EltTy->isIntegerType())
9377 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9380 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9382 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9383 return Success(Elements, E);
9386 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9387 VisitIgnoredValue(E->getSubExpr());
9388 return ZeroInitialization(E);
9391 //===----------------------------------------------------------------------===//
9393 //===----------------------------------------------------------------------===//
9396 class ArrayExprEvaluator
9397 : public ExprEvaluatorBase<ArrayExprEvaluator> {
9402 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9403 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9405 bool Success(const APValue &V, const Expr *E) {
9406 assert(V.isArray() && "expected array");
9411 bool ZeroInitialization(const Expr *E) {
9412 const ConstantArrayType *CAT =
9413 Info.Ctx.getAsConstantArrayType(E->getType());
9417 Result = APValue(APValue::UninitArray(), 0,
9418 CAT->getSize().getZExtValue());
9419 if (!Result.hasArrayFiller()) return true;
9421 // Zero-initialize all elements.
9422 LValue Subobject = This;
9423 Subobject.addArray(Info, E, CAT);
9424 ImplicitValueInitExpr VIE(CAT->getElementType());
9425 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9428 bool VisitCallExpr(const CallExpr *E) {
9429 return handleCallExpr(E, Result, &This);
9431 bool VisitInitListExpr(const InitListExpr *E,
9432 QualType AllocType = QualType());
9433 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9434 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9435 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9436 const LValue &Subobject,
9437 APValue *Value, QualType Type);
9438 bool VisitStringLiteral(const StringLiteral *E,
9439 QualType AllocType = QualType()) {
9440 expandStringLiteral(Info, E, Result, AllocType);
9444 } // end anonymous namespace
9446 static bool EvaluateArray(const Expr *E, const LValue &This,
9447 APValue &Result, EvalInfo &Info) {
9448 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9449 return ArrayExprEvaluator(Info, This, Result).Visit(E);
9452 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9453 APValue &Result, const InitListExpr *ILE,
9454 QualType AllocType) {
9455 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9456 "not an array rvalue");
9457 return ArrayExprEvaluator(Info, This, Result)
9458 .VisitInitListExpr(ILE, AllocType);
9461 // Return true iff the given array filler may depend on the element index.
9462 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9463 // For now, just whitelist non-class value-initialization and initialization
9464 // lists comprised of them.
9465 if (isa<ImplicitValueInitExpr>(FillerExpr))
9467 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9468 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9469 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9477 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9478 QualType AllocType) {
9479 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9480 AllocType.isNull() ? E->getType() : AllocType);
9484 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9485 // an appropriately-typed string literal enclosed in braces.
9486 if (E->isStringLiteralInit()) {
9487 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9488 // FIXME: Support ObjCEncodeExpr here once we support it in
9489 // ArrayExprEvaluator generally.
9492 return VisitStringLiteral(SL, AllocType);
9495 bool Success = true;
9497 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9498 "zero-initialized array shouldn't have any initialized elts");
9500 if (Result.isArray() && Result.hasArrayFiller())
9501 Filler = Result.getArrayFiller();
9503 unsigned NumEltsToInit = E->getNumInits();
9504 unsigned NumElts = CAT->getSize().getZExtValue();
9505 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9507 // If the initializer might depend on the array index, run it for each
9509 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9510 NumEltsToInit = NumElts;
9512 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9513 << NumEltsToInit << ".\n");
9515 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9517 // If the array was previously zero-initialized, preserve the
9518 // zero-initialized values.
9519 if (Filler.hasValue()) {
9520 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9521 Result.getArrayInitializedElt(I) = Filler;
9522 if (Result.hasArrayFiller())
9523 Result.getArrayFiller() = Filler;
9526 LValue Subobject = This;
9527 Subobject.addArray(Info, E, CAT);
9528 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9530 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9531 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9532 Info, Subobject, Init) ||
9533 !HandleLValueArrayAdjustment(Info, Init, Subobject,
9534 CAT->getElementType(), 1)) {
9535 if (!Info.noteFailure())
9541 if (!Result.hasArrayFiller())
9544 // If we get here, we have a trivial filler, which we can just evaluate
9545 // once and splat over the rest of the array elements.
9546 assert(FillerExpr && "no array filler for incomplete init list");
9547 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9548 FillerExpr) && Success;
9551 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9553 if (E->getCommonExpr() &&
9554 !Evaluate(Info.CurrentCall->createTemporary(
9556 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9558 Info, E->getCommonExpr()->getSourceExpr()))
9561 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9563 uint64_t Elements = CAT->getSize().getZExtValue();
9564 Result = APValue(APValue::UninitArray(), Elements, Elements);
9566 LValue Subobject = This;
9567 Subobject.addArray(Info, E, CAT);
9569 bool Success = true;
9570 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9571 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9572 Info, Subobject, E->getSubExpr()) ||
9573 !HandleLValueArrayAdjustment(Info, E, Subobject,
9574 CAT->getElementType(), 1)) {
9575 if (!Info.noteFailure())
9584 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9585 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9588 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9589 const LValue &Subobject,
9592 bool HadZeroInit = Value->hasValue();
9594 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9595 unsigned N = CAT->getSize().getZExtValue();
9597 // Preserve the array filler if we had prior zero-initialization.
9599 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9602 *Value = APValue(APValue::UninitArray(), N, N);
9605 for (unsigned I = 0; I != N; ++I)
9606 Value->getArrayInitializedElt(I) = Filler;
9608 // Initialize the elements.
9609 LValue ArrayElt = Subobject;
9610 ArrayElt.addArray(Info, E, CAT);
9611 for (unsigned I = 0; I != N; ++I)
9612 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9613 CAT->getElementType()) ||
9614 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9615 CAT->getElementType(), 1))
9621 if (!Type->isRecordType())
9624 return RecordExprEvaluator(Info, Subobject, *Value)
9625 .VisitCXXConstructExpr(E, Type);
9628 //===----------------------------------------------------------------------===//
9629 // Integer Evaluation
9631 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9632 // types and back in constant folding. Integer values are thus represented
9633 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9634 //===----------------------------------------------------------------------===//
9637 class IntExprEvaluator
9638 : public ExprEvaluatorBase<IntExprEvaluator> {
9641 IntExprEvaluator(EvalInfo &info, APValue &result)
9642 : ExprEvaluatorBaseTy(info), Result(result) {}
9644 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9645 assert(E->getType()->isIntegralOrEnumerationType() &&
9646 "Invalid evaluation result.");
9647 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9648 "Invalid evaluation result.");
9649 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9650 "Invalid evaluation result.");
9651 Result = APValue(SI);
9654 bool Success(const llvm::APSInt &SI, const Expr *E) {
9655 return Success(SI, E, Result);
9658 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9659 assert(E->getType()->isIntegralOrEnumerationType() &&
9660 "Invalid evaluation result.");
9661 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9662 "Invalid evaluation result.");
9663 Result = APValue(APSInt(I));
9664 Result.getInt().setIsUnsigned(
9665 E->getType()->isUnsignedIntegerOrEnumerationType());
9668 bool Success(const llvm::APInt &I, const Expr *E) {
9669 return Success(I, E, Result);
9672 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9673 assert(E->getType()->isIntegralOrEnumerationType() &&
9674 "Invalid evaluation result.");
9675 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9678 bool Success(uint64_t Value, const Expr *E) {
9679 return Success(Value, E, Result);
9682 bool Success(CharUnits Size, const Expr *E) {
9683 return Success(Size.getQuantity(), E);
9686 bool Success(const APValue &V, const Expr *E) {
9687 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9691 return Success(V.getInt(), E);
9694 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9696 //===--------------------------------------------------------------------===//
9698 //===--------------------------------------------------------------------===//
9700 bool VisitConstantExpr(const ConstantExpr *E);
9702 bool VisitIntegerLiteral(const IntegerLiteral *E) {
9703 return Success(E->getValue(), E);
9705 bool VisitCharacterLiteral(const CharacterLiteral *E) {
9706 return Success(E->getValue(), E);
9709 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9710 bool VisitDeclRefExpr(const DeclRefExpr *E) {
9711 if (CheckReferencedDecl(E, E->getDecl()))
9714 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9716 bool VisitMemberExpr(const MemberExpr *E) {
9717 if (CheckReferencedDecl(E, E->getMemberDecl())) {
9718 VisitIgnoredBaseExpression(E->getBase());
9722 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9725 bool VisitCallExpr(const CallExpr *E);
9726 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9727 bool VisitBinaryOperator(const BinaryOperator *E);
9728 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9729 bool VisitUnaryOperator(const UnaryOperator *E);
9731 bool VisitCastExpr(const CastExpr* E);
9732 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9734 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9735 return Success(E->getValue(), E);
9738 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9739 return Success(E->getValue(), E);
9742 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9743 if (Info.ArrayInitIndex == uint64_t(-1)) {
9744 // We were asked to evaluate this subexpression independent of the
9745 // enclosing ArrayInitLoopExpr. We can't do that.
9749 return Success(Info.ArrayInitIndex, E);
9752 // Note, GNU defines __null as an integer, not a pointer.
9753 bool VisitGNUNullExpr(const GNUNullExpr *E) {
9754 return ZeroInitialization(E);
9757 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9758 return Success(E->getValue(), E);
9761 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9762 return Success(E->getValue(), E);
9765 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9766 return Success(E->getValue(), E);
9769 bool VisitUnaryReal(const UnaryOperator *E);
9770 bool VisitUnaryImag(const UnaryOperator *E);
9772 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
9773 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
9774 bool VisitSourceLocExpr(const SourceLocExpr *E);
9775 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
9776 // FIXME: Missing: array subscript of vector, member of vector
9779 class FixedPointExprEvaluator
9780 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9784 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9785 : ExprEvaluatorBaseTy(info), Result(result) {}
9787 bool Success(const llvm::APInt &I, const Expr *E) {
9789 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9792 bool Success(uint64_t Value, const Expr *E) {
9794 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9797 bool Success(const APValue &V, const Expr *E) {
9798 return Success(V.getFixedPoint(), E);
9801 bool Success(const APFixedPoint &V, const Expr *E) {
9802 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9803 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9804 "Invalid evaluation result.");
9805 Result = APValue(V);
9809 //===--------------------------------------------------------------------===//
9811 //===--------------------------------------------------------------------===//
9813 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9814 return Success(E->getValue(), E);
9817 bool VisitCastExpr(const CastExpr *E);
9818 bool VisitUnaryOperator(const UnaryOperator *E);
9819 bool VisitBinaryOperator(const BinaryOperator *E);
9821 } // end anonymous namespace
9823 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9824 /// produce either the integer value or a pointer.
9826 /// GCC has a heinous extension which folds casts between pointer types and
9827 /// pointer-sized integral types. We support this by allowing the evaluation of
9828 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9829 /// Some simple arithmetic on such values is supported (they are treated much
9831 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
9833 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
9834 return IntExprEvaluator(Info, Result).Visit(E);
9837 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
9839 if (!EvaluateIntegerOrLValue(E, Val, Info))
9842 // FIXME: It would be better to produce the diagnostic for casting
9843 // a pointer to an integer.
9844 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9847 Result = Val.getInt();
9851 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9852 APValue Evaluated = E->EvaluateInContext(
9853 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9854 return Success(Evaluated, E);
9857 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9859 if (E->getType()->isFixedPointType()) {
9861 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9863 if (!Val.isFixedPoint())
9866 Result = Val.getFixedPoint();
9872 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9874 if (E->getType()->isIntegerType()) {
9875 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9877 if (!EvaluateInteger(E, Val, Info))
9879 Result = APFixedPoint(Val, FXSema);
9881 } else if (E->getType()->isFixedPointType()) {
9882 return EvaluateFixedPoint(E, Result, Info);
9887 /// Check whether the given declaration can be directly converted to an integral
9888 /// rvalue. If not, no diagnostic is produced; there are other things we can
9890 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
9891 // Enums are integer constant exprs.
9892 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
9893 // Check for signedness/width mismatches between E type and ECD value.
9894 bool SameSign = (ECD->getInitVal().isSigned()
9895 == E->getType()->isSignedIntegerOrEnumerationType());
9896 bool SameWidth = (ECD->getInitVal().getBitWidth()
9897 == Info.Ctx.getIntWidth(E->getType()));
9898 if (SameSign && SameWidth)
9899 return Success(ECD->getInitVal(), E);
9901 // Get rid of mismatch (otherwise Success assertions will fail)
9902 // by computing a new value matching the type of E.
9903 llvm::APSInt Val = ECD->getInitVal();
9905 Val.setIsSigned(!ECD->getInitVal().isSigned());
9907 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9908 return Success(Val, E);
9914 /// Values returned by __builtin_classify_type, chosen to match the values
9915 /// produced by GCC's builtin.
9916 enum class GCCTypeClass {
9920 // GCC reserves 2 for character types, but instead classifies them as
9925 // GCC reserves 6 for references, but appears to never use it (because
9926 // expressions never have reference type, presumably).
9927 PointerToDataMember = 7,
9930 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9931 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9932 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9933 // uses 12 for that purpose, same as for a class or struct. Maybe it
9934 // internally implements a pointer to member as a struct? Who knows.
9935 PointerToMemberFunction = 12, // Not a bug, see above.
9938 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9939 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9940 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9944 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9947 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9948 assert(!T->isDependentType() && "unexpected dependent type");
9950 QualType CanTy = T.getCanonicalType();
9951 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9953 switch (CanTy->getTypeClass()) {
9954 #define TYPE(ID, BASE)
9955 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9956 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9957 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
9958 #include "clang/AST/TypeNodes.inc"
9960 case Type::DeducedTemplateSpecialization:
9961 llvm_unreachable("unexpected non-canonical or dependent type");
9964 switch (BT->getKind()) {
9965 #define BUILTIN_TYPE(ID, SINGLETON_ID)
9966 #define SIGNED_TYPE(ID, SINGLETON_ID) \
9967 case BuiltinType::ID: return GCCTypeClass::Integer;
9968 #define FLOATING_TYPE(ID, SINGLETON_ID) \
9969 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9970 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9971 case BuiltinType::ID: break;
9972 #include "clang/AST/BuiltinTypes.def"
9973 case BuiltinType::Void:
9974 return GCCTypeClass::Void;
9976 case BuiltinType::Bool:
9977 return GCCTypeClass::Bool;
9979 case BuiltinType::Char_U:
9980 case BuiltinType::UChar:
9981 case BuiltinType::WChar_U:
9982 case BuiltinType::Char8:
9983 case BuiltinType::Char16:
9984 case BuiltinType::Char32:
9985 case BuiltinType::UShort:
9986 case BuiltinType::UInt:
9987 case BuiltinType::ULong:
9988 case BuiltinType::ULongLong:
9989 case BuiltinType::UInt128:
9990 return GCCTypeClass::Integer;
9992 case BuiltinType::UShortAccum:
9993 case BuiltinType::UAccum:
9994 case BuiltinType::ULongAccum:
9995 case BuiltinType::UShortFract:
9996 case BuiltinType::UFract:
9997 case BuiltinType::ULongFract:
9998 case BuiltinType::SatUShortAccum:
9999 case BuiltinType::SatUAccum:
10000 case BuiltinType::SatULongAccum:
10001 case BuiltinType::SatUShortFract:
10002 case BuiltinType::SatUFract:
10003 case BuiltinType::SatULongFract:
10004 return GCCTypeClass::None;
10006 case BuiltinType::NullPtr:
10008 case BuiltinType::ObjCId:
10009 case BuiltinType::ObjCClass:
10010 case BuiltinType::ObjCSel:
10011 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10012 case BuiltinType::Id:
10013 #include "clang/Basic/OpenCLImageTypes.def"
10014 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10015 case BuiltinType::Id:
10016 #include "clang/Basic/OpenCLExtensionTypes.def"
10017 case BuiltinType::OCLSampler:
10018 case BuiltinType::OCLEvent:
10019 case BuiltinType::OCLClkEvent:
10020 case BuiltinType::OCLQueue:
10021 case BuiltinType::OCLReserveID:
10022 #define SVE_TYPE(Name, Id, SingletonId) \
10023 case BuiltinType::Id:
10024 #include "clang/Basic/AArch64SVEACLETypes.def"
10025 return GCCTypeClass::None;
10027 case BuiltinType::Dependent:
10028 llvm_unreachable("unexpected dependent type");
10030 llvm_unreachable("unexpected placeholder type");
10033 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10035 case Type::Pointer:
10036 case Type::ConstantArray:
10037 case Type::VariableArray:
10038 case Type::IncompleteArray:
10039 case Type::FunctionNoProto:
10040 case Type::FunctionProto:
10041 return GCCTypeClass::Pointer;
10043 case Type::MemberPointer:
10044 return CanTy->isMemberDataPointerType()
10045 ? GCCTypeClass::PointerToDataMember
10046 : GCCTypeClass::PointerToMemberFunction;
10048 case Type::Complex:
10049 return GCCTypeClass::Complex;
10052 return CanTy->isUnionType() ? GCCTypeClass::Union
10053 : GCCTypeClass::ClassOrStruct;
10056 // GCC classifies _Atomic T the same as T.
10057 return EvaluateBuiltinClassifyType(
10058 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10060 case Type::BlockPointer:
10062 case Type::ExtVector:
10063 case Type::ObjCObject:
10064 case Type::ObjCInterface:
10065 case Type::ObjCObjectPointer:
10067 // GCC classifies vectors as None. We follow its lead and classify all
10068 // other types that don't fit into the regular classification the same way.
10069 return GCCTypeClass::None;
10071 case Type::LValueReference:
10072 case Type::RValueReference:
10073 llvm_unreachable("invalid type for expression");
10076 llvm_unreachable("unexpected type class");
10079 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10081 static GCCTypeClass
10082 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10083 // If no argument was supplied, default to None. This isn't
10084 // ideal, however it is what gcc does.
10085 if (E->getNumArgs() == 0)
10086 return GCCTypeClass::None;
10088 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10089 // being an ICE, but still folds it to a constant using the type of the first
10091 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10094 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10095 /// __builtin_constant_p when applied to the given pointer.
10097 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10098 /// or it points to the first character of a string literal.
10099 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10100 APValue::LValueBase Base = LV.getLValueBase();
10101 if (Base.isNull()) {
10102 // A null base is acceptable.
10104 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10105 if (!isa<StringLiteral>(E))
10107 return LV.getLValueOffset().isZero();
10108 } else if (Base.is<TypeInfoLValue>()) {
10109 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10110 // evaluate to true.
10113 // Any other base is not constant enough for GCC.
10118 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10119 /// GCC as we can manage.
10120 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10121 // This evaluation is not permitted to have side-effects, so evaluate it in
10122 // a speculative evaluation context.
10123 SpeculativeEvaluationRAII SpeculativeEval(Info);
10125 // Constant-folding is always enabled for the operand of __builtin_constant_p
10126 // (even when the enclosing evaluation context otherwise requires a strict
10127 // language-specific constant expression).
10128 FoldConstant Fold(Info, true);
10130 QualType ArgType = Arg->getType();
10132 // __builtin_constant_p always has one operand. The rules which gcc follows
10133 // are not precisely documented, but are as follows:
10135 // - If the operand is of integral, floating, complex or enumeration type,
10136 // and can be folded to a known value of that type, it returns 1.
10137 // - If the operand can be folded to a pointer to the first character
10138 // of a string literal (or such a pointer cast to an integral type)
10139 // or to a null pointer or an integer cast to a pointer, it returns 1.
10141 // Otherwise, it returns 0.
10143 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10144 // its support for this did not work prior to GCC 9 and is not yet well
10146 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10147 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10148 ArgType->isNullPtrType()) {
10150 if (!::EvaluateAsRValue(Info, Arg, V)) {
10151 Fold.keepDiagnostics();
10155 // For a pointer (possibly cast to integer), there are special rules.
10156 if (V.getKind() == APValue::LValue)
10157 return EvaluateBuiltinConstantPForLValue(V);
10159 // Otherwise, any constant value is good enough.
10160 return V.hasValue();
10163 // Anything else isn't considered to be sufficiently constant.
10167 /// Retrieves the "underlying object type" of the given expression,
10168 /// as used by __builtin_object_size.
10169 static QualType getObjectType(APValue::LValueBase B) {
10170 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10171 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10172 return VD->getType();
10173 } else if (const Expr *E = B.get<const Expr*>()) {
10174 if (isa<CompoundLiteralExpr>(E))
10175 return E->getType();
10176 } else if (B.is<TypeInfoLValue>()) {
10177 return B.getTypeInfoType();
10178 } else if (B.is<DynamicAllocLValue>()) {
10179 return B.getDynamicAllocType();
10185 /// A more selective version of E->IgnoreParenCasts for
10186 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10187 /// to change the type of E.
10188 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10190 /// Always returns an RValue with a pointer representation.
10191 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10192 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10194 auto *NoParens = E->IgnoreParens();
10195 auto *Cast = dyn_cast<CastExpr>(NoParens);
10196 if (Cast == nullptr)
10199 // We only conservatively allow a few kinds of casts, because this code is
10200 // inherently a simple solution that seeks to support the common case.
10201 auto CastKind = Cast->getCastKind();
10202 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10203 CastKind != CK_AddressSpaceConversion)
10206 auto *SubExpr = Cast->getSubExpr();
10207 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10209 return ignorePointerCastsAndParens(SubExpr);
10212 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10213 /// record layout. e.g.
10214 /// struct { struct { int a, b; } fst, snd; } obj;
10217 /// obj.fst.a // no
10218 /// obj.fst.b // no
10219 /// obj.snd.a // no
10220 /// obj.snd.b // yes
10222 /// Please note: this function is specialized for how __builtin_object_size
10223 /// views "objects".
10225 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10226 /// correct result, it will always return true.
10227 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10228 assert(!LVal.Designator.Invalid);
10230 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10231 const RecordDecl *Parent = FD->getParent();
10232 Invalid = Parent->isInvalidDecl();
10233 if (Invalid || Parent->isUnion())
10235 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10236 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10239 auto &Base = LVal.getLValueBase();
10240 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10241 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10243 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10245 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10246 for (auto *FD : IFD->chain()) {
10248 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10255 QualType BaseType = getType(Base);
10256 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10257 // If we don't know the array bound, conservatively assume we're looking at
10258 // the final array element.
10260 if (BaseType->isIncompleteArrayType())
10261 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10263 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10266 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10267 const auto &Entry = LVal.Designator.Entries[I];
10268 if (BaseType->isArrayType()) {
10269 // Because __builtin_object_size treats arrays as objects, we can ignore
10270 // the index iff this is the last array in the Designator.
10273 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10274 uint64_t Index = Entry.getAsArrayIndex();
10275 if (Index + 1 != CAT->getSize())
10277 BaseType = CAT->getElementType();
10278 } else if (BaseType->isAnyComplexType()) {
10279 const auto *CT = BaseType->castAs<ComplexType>();
10280 uint64_t Index = Entry.getAsArrayIndex();
10283 BaseType = CT->getElementType();
10284 } else if (auto *FD = getAsField(Entry)) {
10286 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10288 BaseType = FD->getType();
10290 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10297 /// Tests to see if the LValue has a user-specified designator (that isn't
10298 /// necessarily valid). Note that this always returns 'true' if the LValue has
10299 /// an unsized array as its first designator entry, because there's currently no
10300 /// way to tell if the user typed *foo or foo[0].
10301 static bool refersToCompleteObject(const LValue &LVal) {
10302 if (LVal.Designator.Invalid)
10305 if (!LVal.Designator.Entries.empty())
10306 return LVal.Designator.isMostDerivedAnUnsizedArray();
10308 if (!LVal.InvalidBase)
10311 // If `E` is a MemberExpr, then the first part of the designator is hiding in
10313 const auto *E = LVal.Base.dyn_cast<const Expr *>();
10314 return !E || !isa<MemberExpr>(E);
10317 /// Attempts to detect a user writing into a piece of memory that's impossible
10318 /// to figure out the size of by just using types.
10319 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10320 const SubobjectDesignator &Designator = LVal.Designator;
10322 // - Users can only write off of the end when we have an invalid base. Invalid
10323 // bases imply we don't know where the memory came from.
10324 // - We used to be a bit more aggressive here; we'd only be conservative if
10325 // the array at the end was flexible, or if it had 0 or 1 elements. This
10326 // broke some common standard library extensions (PR30346), but was
10327 // otherwise seemingly fine. It may be useful to reintroduce this behavior
10328 // with some sort of whitelist. OTOH, it seems that GCC is always
10329 // conservative with the last element in structs (if it's an array), so our
10330 // current behavior is more compatible than a whitelisting approach would
10332 return LVal.InvalidBase &&
10333 Designator.Entries.size() == Designator.MostDerivedPathLength &&
10334 Designator.MostDerivedIsArrayElement &&
10335 isDesignatorAtObjectEnd(Ctx, LVal);
10338 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10339 /// Fails if the conversion would cause loss of precision.
10340 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10341 CharUnits &Result) {
10342 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10343 if (Int.ugt(CharUnitsMax))
10345 Result = CharUnits::fromQuantity(Int.getZExtValue());
10349 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10350 /// determine how many bytes exist from the beginning of the object to either
10351 /// the end of the current subobject, or the end of the object itself, depending
10352 /// on what the LValue looks like + the value of Type.
10354 /// If this returns false, the value of Result is undefined.
10355 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10356 unsigned Type, const LValue &LVal,
10357 CharUnits &EndOffset) {
10358 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10360 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10361 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10363 return HandleSizeof(Info, ExprLoc, Ty, Result);
10366 // We want to evaluate the size of the entire object. This is a valid fallback
10367 // for when Type=1 and the designator is invalid, because we're asked for an
10369 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10370 // Type=3 wants a lower bound, so we can't fall back to this.
10371 if (Type == 3 && !DetermineForCompleteObject)
10374 llvm::APInt APEndOffset;
10375 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10376 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10377 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10379 if (LVal.InvalidBase)
10382 QualType BaseTy = getObjectType(LVal.getLValueBase());
10383 return CheckedHandleSizeof(BaseTy, EndOffset);
10386 // We want to evaluate the size of a subobject.
10387 const SubobjectDesignator &Designator = LVal.Designator;
10389 // The following is a moderately common idiom in C:
10391 // struct Foo { int a; char c[1]; };
10392 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10393 // strcpy(&F->c[0], Bar);
10395 // In order to not break too much legacy code, we need to support it.
10396 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10397 // If we can resolve this to an alloc_size call, we can hand that back,
10398 // because we know for certain how many bytes there are to write to.
10399 llvm::APInt APEndOffset;
10400 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10401 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10402 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10404 // If we cannot determine the size of the initial allocation, then we can't
10405 // given an accurate upper-bound. However, we are still able to give
10406 // conservative lower-bounds for Type=3.
10411 CharUnits BytesPerElem;
10412 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10415 // According to the GCC documentation, we want the size of the subobject
10416 // denoted by the pointer. But that's not quite right -- what we actually
10417 // want is the size of the immediately-enclosing array, if there is one.
10418 int64_t ElemsRemaining;
10419 if (Designator.MostDerivedIsArrayElement &&
10420 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10421 uint64_t ArraySize = Designator.getMostDerivedArraySize();
10422 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10423 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10425 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10428 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10432 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10433 /// returns true and stores the result in @p Size.
10435 /// If @p WasError is non-null, this will report whether the failure to evaluate
10436 /// is to be treated as an Error in IntExprEvaluator.
10437 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10438 EvalInfo &Info, uint64_t &Size) {
10439 // Determine the denoted object.
10442 // The operand of __builtin_object_size is never evaluated for side-effects.
10443 // If there are any, but we can determine the pointed-to object anyway, then
10444 // ignore the side-effects.
10445 SpeculativeEvaluationRAII SpeculativeEval(Info);
10446 IgnoreSideEffectsRAII Fold(Info);
10448 if (E->isGLValue()) {
10449 // It's possible for us to be given GLValues if we're called via
10450 // Expr::tryEvaluateObjectSize.
10452 if (!EvaluateAsRValue(Info, E, RVal))
10454 LVal.setFrom(Info.Ctx, RVal);
10455 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10456 /*InvalidBaseOK=*/true))
10460 // If we point to before the start of the object, there are no accessible
10462 if (LVal.getLValueOffset().isNegative()) {
10467 CharUnits EndOffset;
10468 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10471 // If we've fallen outside of the end offset, just pretend there's nothing to
10472 // write to/read from.
10473 if (EndOffset <= LVal.getLValueOffset())
10476 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10480 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10481 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10482 if (E->getResultAPValueKind() != APValue::None)
10483 return Success(E->getAPValueResult(), E);
10484 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10487 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10488 if (unsigned BuiltinOp = E->getBuiltinCallee())
10489 return VisitBuiltinCallExpr(E, BuiltinOp);
10491 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10494 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10495 unsigned BuiltinOp) {
10496 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
10498 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10500 case Builtin::BI__builtin_dynamic_object_size:
10501 case Builtin::BI__builtin_object_size: {
10502 // The type was checked when we built the expression.
10504 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10505 assert(Type <= 3 && "unexpected type");
10508 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10509 return Success(Size, E);
10511 if (E->getArg(0)->HasSideEffects(Info.Ctx))
10512 return Success((Type & 2) ? 0 : -1, E);
10514 // Expression had no side effects, but we couldn't statically determine the
10515 // size of the referenced object.
10516 switch (Info.EvalMode) {
10517 case EvalInfo::EM_ConstantExpression:
10518 case EvalInfo::EM_ConstantFold:
10519 case EvalInfo::EM_IgnoreSideEffects:
10520 // Leave it to IR generation.
10522 case EvalInfo::EM_ConstantExpressionUnevaluated:
10523 // Reduce it to a constant now.
10524 return Success((Type & 2) ? 0 : -1, E);
10527 llvm_unreachable("unexpected EvalMode");
10530 case Builtin::BI__builtin_os_log_format_buffer_size: {
10531 analyze_os_log::OSLogBufferLayout Layout;
10532 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10533 return Success(Layout.size().getQuantity(), E);
10536 case Builtin::BI__builtin_bswap16:
10537 case Builtin::BI__builtin_bswap32:
10538 case Builtin::BI__builtin_bswap64: {
10540 if (!EvaluateInteger(E->getArg(0), Val, Info))
10543 return Success(Val.byteSwap(), E);
10546 case Builtin::BI__builtin_classify_type:
10547 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10549 case Builtin::BI__builtin_clrsb:
10550 case Builtin::BI__builtin_clrsbl:
10551 case Builtin::BI__builtin_clrsbll: {
10553 if (!EvaluateInteger(E->getArg(0), Val, Info))
10556 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10559 case Builtin::BI__builtin_clz:
10560 case Builtin::BI__builtin_clzl:
10561 case Builtin::BI__builtin_clzll:
10562 case Builtin::BI__builtin_clzs: {
10564 if (!EvaluateInteger(E->getArg(0), Val, Info))
10569 return Success(Val.countLeadingZeros(), E);
10572 case Builtin::BI__builtin_constant_p: {
10573 const Expr *Arg = E->getArg(0);
10574 if (EvaluateBuiltinConstantP(Info, Arg))
10575 return Success(true, E);
10576 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10577 // Outside a constant context, eagerly evaluate to false in the presence
10578 // of side-effects in order to avoid -Wunsequenced false-positives in
10579 // a branch on __builtin_constant_p(expr).
10580 return Success(false, E);
10582 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10586 case Builtin::BI__builtin_is_constant_evaluated:
10587 return Success(Info.InConstantContext, E);
10589 case Builtin::BI__builtin_ctz:
10590 case Builtin::BI__builtin_ctzl:
10591 case Builtin::BI__builtin_ctzll:
10592 case Builtin::BI__builtin_ctzs: {
10594 if (!EvaluateInteger(E->getArg(0), Val, Info))
10599 return Success(Val.countTrailingZeros(), E);
10602 case Builtin::BI__builtin_eh_return_data_regno: {
10603 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10604 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10605 return Success(Operand, E);
10608 case Builtin::BI__builtin_expect:
10609 return Visit(E->getArg(0));
10611 case Builtin::BI__builtin_ffs:
10612 case Builtin::BI__builtin_ffsl:
10613 case Builtin::BI__builtin_ffsll: {
10615 if (!EvaluateInteger(E->getArg(0), Val, Info))
10618 unsigned N = Val.countTrailingZeros();
10619 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10622 case Builtin::BI__builtin_fpclassify: {
10624 if (!EvaluateFloat(E->getArg(5), Val, Info))
10627 switch (Val.getCategory()) {
10628 case APFloat::fcNaN: Arg = 0; break;
10629 case APFloat::fcInfinity: Arg = 1; break;
10630 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10631 case APFloat::fcZero: Arg = 4; break;
10633 return Visit(E->getArg(Arg));
10636 case Builtin::BI__builtin_isinf_sign: {
10638 return EvaluateFloat(E->getArg(0), Val, Info) &&
10639 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10642 case Builtin::BI__builtin_isinf: {
10644 return EvaluateFloat(E->getArg(0), Val, Info) &&
10645 Success(Val.isInfinity() ? 1 : 0, E);
10648 case Builtin::BI__builtin_isfinite: {
10650 return EvaluateFloat(E->getArg(0), Val, Info) &&
10651 Success(Val.isFinite() ? 1 : 0, E);
10654 case Builtin::BI__builtin_isnan: {
10656 return EvaluateFloat(E->getArg(0), Val, Info) &&
10657 Success(Val.isNaN() ? 1 : 0, E);
10660 case Builtin::BI__builtin_isnormal: {
10662 return EvaluateFloat(E->getArg(0), Val, Info) &&
10663 Success(Val.isNormal() ? 1 : 0, E);
10666 case Builtin::BI__builtin_parity:
10667 case Builtin::BI__builtin_parityl:
10668 case Builtin::BI__builtin_parityll: {
10670 if (!EvaluateInteger(E->getArg(0), Val, Info))
10673 return Success(Val.countPopulation() % 2, E);
10676 case Builtin::BI__builtin_popcount:
10677 case Builtin::BI__builtin_popcountl:
10678 case Builtin::BI__builtin_popcountll: {
10680 if (!EvaluateInteger(E->getArg(0), Val, Info))
10683 return Success(Val.countPopulation(), E);
10686 case Builtin::BIstrlen:
10687 case Builtin::BIwcslen:
10688 // A call to strlen is not a constant expression.
10689 if (Info.getLangOpts().CPlusPlus11)
10690 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10691 << /*isConstexpr*/0 << /*isConstructor*/0
10692 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10694 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10696 case Builtin::BI__builtin_strlen:
10697 case Builtin::BI__builtin_wcslen: {
10698 // As an extension, we support __builtin_strlen() as a constant expression,
10699 // and support folding strlen() to a constant.
10701 if (!EvaluatePointer(E->getArg(0), String, Info))
10704 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10706 // Fast path: if it's a string literal, search the string value.
10707 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10708 String.getLValueBase().dyn_cast<const Expr *>())) {
10709 // The string literal may have embedded null characters. Find the first
10710 // one and truncate there.
10711 StringRef Str = S->getBytes();
10712 int64_t Off = String.Offset.getQuantity();
10713 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
10714 S->getCharByteWidth() == 1 &&
10715 // FIXME: Add fast-path for wchar_t too.
10716 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
10717 Str = Str.substr(Off);
10719 StringRef::size_type Pos = Str.find(0);
10720 if (Pos != StringRef::npos)
10721 Str = Str.substr(0, Pos);
10723 return Success(Str.size(), E);
10726 // Fall through to slow path to issue appropriate diagnostic.
10729 // Slow path: scan the bytes of the string looking for the terminating 0.
10730 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10732 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10735 if (!Char.getInt())
10736 return Success(Strlen, E);
10737 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10742 case Builtin::BIstrcmp:
10743 case Builtin::BIwcscmp:
10744 case Builtin::BIstrncmp:
10745 case Builtin::BIwcsncmp:
10746 case Builtin::BImemcmp:
10747 case Builtin::BIbcmp:
10748 case Builtin::BIwmemcmp:
10749 // A call to strlen is not a constant expression.
10750 if (Info.getLangOpts().CPlusPlus11)
10751 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10752 << /*isConstexpr*/0 << /*isConstructor*/0
10753 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10755 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10757 case Builtin::BI__builtin_strcmp:
10758 case Builtin::BI__builtin_wcscmp:
10759 case Builtin::BI__builtin_strncmp:
10760 case Builtin::BI__builtin_wcsncmp:
10761 case Builtin::BI__builtin_memcmp:
10762 case Builtin::BI__builtin_bcmp:
10763 case Builtin::BI__builtin_wmemcmp: {
10764 LValue String1, String2;
10765 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10766 !EvaluatePointer(E->getArg(1), String2, Info))
10769 uint64_t MaxLength = uint64_t(-1);
10770 if (BuiltinOp != Builtin::BIstrcmp &&
10771 BuiltinOp != Builtin::BIwcscmp &&
10772 BuiltinOp != Builtin::BI__builtin_strcmp &&
10773 BuiltinOp != Builtin::BI__builtin_wcscmp) {
10775 if (!EvaluateInteger(E->getArg(2), N, Info))
10777 MaxLength = N.getExtValue();
10780 // Empty substrings compare equal by definition.
10781 if (MaxLength == 0u)
10782 return Success(0, E);
10784 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10785 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10786 String1.Designator.Invalid || String2.Designator.Invalid)
10789 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10790 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10792 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
10793 BuiltinOp == Builtin::BIbcmp ||
10794 BuiltinOp == Builtin::BI__builtin_memcmp ||
10795 BuiltinOp == Builtin::BI__builtin_bcmp;
10797 assert(IsRawByte ||
10798 (Info.Ctx.hasSameUnqualifiedType(
10799 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10800 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10802 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10803 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10804 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10805 Char1.isInt() && Char2.isInt();
10807 const auto &AdvanceElems = [&] {
10808 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10809 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10813 uint64_t BytesRemaining = MaxLength;
10814 // Pointers to const void may point to objects of incomplete type.
10815 if (CharTy1->isIncompleteType()) {
10816 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10819 if (CharTy2->isIncompleteType()) {
10820 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10823 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10824 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10825 // Give up on comparing between elements with disparate widths.
10826 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10828 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10829 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10830 "following loop considers at least one element");
10832 APValue Char1, Char2;
10833 if (!ReadCurElems(Char1, Char2))
10835 // We have compatible in-memory widths, but a possible type and
10836 // (for `bool`) internal representation mismatch.
10837 // Assuming two's complement representation, including 0 for `false` and
10838 // 1 for `true`, we can check an appropriate number of elements for
10839 // equality even if they are not byte-sized.
10840 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10841 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10842 if (Char1InMem.ne(Char2InMem)) {
10843 // If the elements are byte-sized, then we can produce a three-way
10844 // comparison result in a straightforward manner.
10845 if (BytesPerElement == 1u) {
10846 // memcmp always compares unsigned chars.
10847 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10849 // The result is byte-order sensitive, and we have multibyte elements.
10850 // FIXME: We can compare the remaining bytes in the correct order.
10853 if (!AdvanceElems())
10855 if (BytesRemaining <= BytesPerElement)
10857 BytesRemaining -= BytesPerElement;
10859 // Enough elements are equal to account for the memcmp limit.
10860 return Success(0, E);
10864 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10865 BuiltinOp != Builtin::BIwmemcmp &&
10866 BuiltinOp != Builtin::BI__builtin_memcmp &&
10867 BuiltinOp != Builtin::BI__builtin_bcmp &&
10868 BuiltinOp != Builtin::BI__builtin_wmemcmp);
10869 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10870 BuiltinOp == Builtin::BIwcsncmp ||
10871 BuiltinOp == Builtin::BIwmemcmp ||
10872 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10873 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10874 BuiltinOp == Builtin::BI__builtin_wmemcmp;
10876 for (; MaxLength; --MaxLength) {
10877 APValue Char1, Char2;
10878 if (!ReadCurElems(Char1, Char2))
10880 if (Char1.getInt() != Char2.getInt()) {
10881 if (IsWide) // wmemcmp compares with wchar_t signedness.
10882 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10883 // memcmp always compares unsigned chars.
10884 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10886 if (StopAtNull && !Char1.getInt())
10887 return Success(0, E);
10888 assert(!(StopAtNull && !Char2.getInt()));
10889 if (!AdvanceElems())
10892 // We hit the strncmp / memcmp limit.
10893 return Success(0, E);
10896 case Builtin::BI__atomic_always_lock_free:
10897 case Builtin::BI__atomic_is_lock_free:
10898 case Builtin::BI__c11_atomic_is_lock_free: {
10900 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10903 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10904 // of two less than the maximum inline atomic width, we know it is
10905 // lock-free. If the size isn't a power of two, or greater than the
10906 // maximum alignment where we promote atomics, we know it is not lock-free
10907 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10908 // the answer can only be determined at runtime; for example, 16-byte
10909 // atomics have lock-free implementations on some, but not all,
10910 // x86-64 processors.
10912 // Check power-of-two.
10913 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
10914 if (Size.isPowerOfTwo()) {
10915 // Check against inlining width.
10916 unsigned InlineWidthBits =
10917 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10918 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10919 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10920 Size == CharUnits::One() ||
10921 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10922 Expr::NPC_NeverValueDependent))
10923 // OK, we will inline appropriately-aligned operations of this size,
10924 // and _Atomic(T) is appropriately-aligned.
10925 return Success(1, E);
10927 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10928 castAs<PointerType>()->getPointeeType();
10929 if (!PointeeType->isIncompleteType() &&
10930 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10931 // OK, we will inline operations on this object.
10932 return Success(1, E);
10937 // Avoid emiting call for runtime decision on PowerPC 32-bit
10938 // The lock free possibilities on this platform are covered by the lines
10939 // above and we know in advance other cases require lock
10940 if (Info.Ctx.getTargetInfo().getTriple().getArch() == llvm::Triple::ppc) {
10941 return Success(0, E);
10944 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10945 Success(0, E) : Error(E);
10947 case Builtin::BIomp_is_initial_device:
10948 // We can decide statically which value the runtime would return if called.
10949 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
10950 case Builtin::BI__builtin_add_overflow:
10951 case Builtin::BI__builtin_sub_overflow:
10952 case Builtin::BI__builtin_mul_overflow:
10953 case Builtin::BI__builtin_sadd_overflow:
10954 case Builtin::BI__builtin_uadd_overflow:
10955 case Builtin::BI__builtin_uaddl_overflow:
10956 case Builtin::BI__builtin_uaddll_overflow:
10957 case Builtin::BI__builtin_usub_overflow:
10958 case Builtin::BI__builtin_usubl_overflow:
10959 case Builtin::BI__builtin_usubll_overflow:
10960 case Builtin::BI__builtin_umul_overflow:
10961 case Builtin::BI__builtin_umull_overflow:
10962 case Builtin::BI__builtin_umulll_overflow:
10963 case Builtin::BI__builtin_saddl_overflow:
10964 case Builtin::BI__builtin_saddll_overflow:
10965 case Builtin::BI__builtin_ssub_overflow:
10966 case Builtin::BI__builtin_ssubl_overflow:
10967 case Builtin::BI__builtin_ssubll_overflow:
10968 case Builtin::BI__builtin_smul_overflow:
10969 case Builtin::BI__builtin_smull_overflow:
10970 case Builtin::BI__builtin_smulll_overflow: {
10971 LValue ResultLValue;
10974 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10975 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10976 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10977 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10981 bool DidOverflow = false;
10983 // If the types don't have to match, enlarge all 3 to the largest of them.
10984 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10985 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10986 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10987 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10988 ResultType->isSignedIntegerOrEnumerationType();
10989 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10990 ResultType->isSignedIntegerOrEnumerationType();
10991 uint64_t LHSSize = LHS.getBitWidth();
10992 uint64_t RHSSize = RHS.getBitWidth();
10993 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10994 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10996 // Add an additional bit if the signedness isn't uniformly agreed to. We
10997 // could do this ONLY if there is a signed and an unsigned that both have
10998 // MaxBits, but the code to check that is pretty nasty. The issue will be
10999 // caught in the shrink-to-result later anyway.
11000 if (IsSigned && !AllSigned)
11003 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11004 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11005 Result = APSInt(MaxBits, !IsSigned);
11008 // Find largest int.
11009 switch (BuiltinOp) {
11011 llvm_unreachable("Invalid value for BuiltinOp");
11012 case Builtin::BI__builtin_add_overflow:
11013 case Builtin::BI__builtin_sadd_overflow:
11014 case Builtin::BI__builtin_saddl_overflow:
11015 case Builtin::BI__builtin_saddll_overflow:
11016 case Builtin::BI__builtin_uadd_overflow:
11017 case Builtin::BI__builtin_uaddl_overflow:
11018 case Builtin::BI__builtin_uaddll_overflow:
11019 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11020 : LHS.uadd_ov(RHS, DidOverflow);
11022 case Builtin::BI__builtin_sub_overflow:
11023 case Builtin::BI__builtin_ssub_overflow:
11024 case Builtin::BI__builtin_ssubl_overflow:
11025 case Builtin::BI__builtin_ssubll_overflow:
11026 case Builtin::BI__builtin_usub_overflow:
11027 case Builtin::BI__builtin_usubl_overflow:
11028 case Builtin::BI__builtin_usubll_overflow:
11029 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11030 : LHS.usub_ov(RHS, DidOverflow);
11032 case Builtin::BI__builtin_mul_overflow:
11033 case Builtin::BI__builtin_smul_overflow:
11034 case Builtin::BI__builtin_smull_overflow:
11035 case Builtin::BI__builtin_smulll_overflow:
11036 case Builtin::BI__builtin_umul_overflow:
11037 case Builtin::BI__builtin_umull_overflow:
11038 case Builtin::BI__builtin_umulll_overflow:
11039 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11040 : LHS.umul_ov(RHS, DidOverflow);
11044 // In the case where multiple sizes are allowed, truncate and see if
11045 // the values are the same.
11046 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11047 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11048 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11049 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11050 // since it will give us the behavior of a TruncOrSelf in the case where
11051 // its parameter <= its size. We previously set Result to be at least the
11052 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11053 // will work exactly like TruncOrSelf.
11054 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11055 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11057 if (!APSInt::isSameValue(Temp, Result))
11058 DidOverflow = true;
11062 APValue APV{Result};
11063 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11065 return Success(DidOverflow, E);
11070 /// Determine whether this is a pointer past the end of the complete
11071 /// object referred to by the lvalue.
11072 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11073 const LValue &LV) {
11074 // A null pointer can be viewed as being "past the end" but we don't
11075 // choose to look at it that way here.
11076 if (!LV.getLValueBase())
11079 // If the designator is valid and refers to a subobject, we're not pointing
11081 if (!LV.getLValueDesignator().Invalid &&
11082 !LV.getLValueDesignator().isOnePastTheEnd())
11085 // A pointer to an incomplete type might be past-the-end if the type's size is
11086 // zero. We cannot tell because the type is incomplete.
11087 QualType Ty = getType(LV.getLValueBase());
11088 if (Ty->isIncompleteType())
11091 // We're a past-the-end pointer if we point to the byte after the object,
11092 // no matter what our type or path is.
11093 auto Size = Ctx.getTypeSizeInChars(Ty);
11094 return LV.getLValueOffset() == Size;
11099 /// Data recursive integer evaluator of certain binary operators.
11101 /// We use a data recursive algorithm for binary operators so that we are able
11102 /// to handle extreme cases of chained binary operators without causing stack
11104 class DataRecursiveIntBinOpEvaluator {
11105 struct EvalResult {
11109 EvalResult() : Failed(false) { }
11111 void swap(EvalResult &RHS) {
11113 Failed = RHS.Failed;
11114 RHS.Failed = false;
11120 EvalResult LHSResult; // meaningful only for binary operator expression.
11121 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11124 Job(Job &&) = default;
11126 void startSpeculativeEval(EvalInfo &Info) {
11127 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11131 SpeculativeEvaluationRAII SpecEvalRAII;
11134 SmallVector<Job, 16> Queue;
11136 IntExprEvaluator &IntEval;
11138 APValue &FinalResult;
11141 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11142 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11144 /// True if \param E is a binary operator that we are going to handle
11145 /// data recursively.
11146 /// We handle binary operators that are comma, logical, or that have operands
11147 /// with integral or enumeration type.
11148 static bool shouldEnqueue(const BinaryOperator *E) {
11149 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11150 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11151 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11152 E->getRHS()->getType()->isIntegralOrEnumerationType());
11155 bool Traverse(const BinaryOperator *E) {
11157 EvalResult PrevResult;
11158 while (!Queue.empty())
11159 process(PrevResult);
11161 if (PrevResult.Failed) return false;
11163 FinalResult.swap(PrevResult.Val);
11168 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11169 return IntEval.Success(Value, E, Result);
11171 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11172 return IntEval.Success(Value, E, Result);
11174 bool Error(const Expr *E) {
11175 return IntEval.Error(E);
11177 bool Error(const Expr *E, diag::kind D) {
11178 return IntEval.Error(E, D);
11181 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11182 return Info.CCEDiag(E, D);
11185 // Returns true if visiting the RHS is necessary, false otherwise.
11186 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11187 bool &SuppressRHSDiags);
11189 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11190 const BinaryOperator *E, APValue &Result);
11192 void EvaluateExpr(const Expr *E, EvalResult &Result) {
11193 Result.Failed = !Evaluate(Result.Val, Info, E);
11195 Result.Val = APValue();
11198 void process(EvalResult &Result);
11200 void enqueue(const Expr *E) {
11201 E = E->IgnoreParens();
11202 Queue.resize(Queue.size()+1);
11203 Queue.back().E = E;
11204 Queue.back().Kind = Job::AnyExprKind;
11210 bool DataRecursiveIntBinOpEvaluator::
11211 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11212 bool &SuppressRHSDiags) {
11213 if (E->getOpcode() == BO_Comma) {
11214 // Ignore LHS but note if we could not evaluate it.
11215 if (LHSResult.Failed)
11216 return Info.noteSideEffect();
11220 if (E->isLogicalOp()) {
11222 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11223 // We were able to evaluate the LHS, see if we can get away with not
11224 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11225 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11226 Success(LHSAsBool, E, LHSResult.Val);
11227 return false; // Ignore RHS
11230 LHSResult.Failed = true;
11232 // Since we weren't able to evaluate the left hand side, it
11233 // might have had side effects.
11234 if (!Info.noteSideEffect())
11237 // We can't evaluate the LHS; however, sometimes the result
11238 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11239 // Don't ignore RHS and suppress diagnostics from this arm.
11240 SuppressRHSDiags = true;
11246 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11247 E->getRHS()->getType()->isIntegralOrEnumerationType());
11249 if (LHSResult.Failed && !Info.noteFailure())
11250 return false; // Ignore RHS;
11255 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11257 // Compute the new offset in the appropriate width, wrapping at 64 bits.
11258 // FIXME: When compiling for a 32-bit target, we should use 32-bit
11260 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11261 CharUnits &Offset = LVal.getLValueOffset();
11262 uint64_t Offset64 = Offset.getQuantity();
11263 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11264 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11265 : Offset64 + Index64);
11268 bool DataRecursiveIntBinOpEvaluator::
11269 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11270 const BinaryOperator *E, APValue &Result) {
11271 if (E->getOpcode() == BO_Comma) {
11272 if (RHSResult.Failed)
11274 Result = RHSResult.Val;
11278 if (E->isLogicalOp()) {
11279 bool lhsResult, rhsResult;
11280 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11281 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11285 if (E->getOpcode() == BO_LOr)
11286 return Success(lhsResult || rhsResult, E, Result);
11288 return Success(lhsResult && rhsResult, E, Result);
11292 // We can't evaluate the LHS; however, sometimes the result
11293 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11294 if (rhsResult == (E->getOpcode() == BO_LOr))
11295 return Success(rhsResult, E, Result);
11302 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11303 E->getRHS()->getType()->isIntegralOrEnumerationType());
11305 if (LHSResult.Failed || RHSResult.Failed)
11308 const APValue &LHSVal = LHSResult.Val;
11309 const APValue &RHSVal = RHSResult.Val;
11311 // Handle cases like (unsigned long)&a + 4.
11312 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11314 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11318 // Handle cases like 4 + (unsigned long)&a
11319 if (E->getOpcode() == BO_Add &&
11320 RHSVal.isLValue() && LHSVal.isInt()) {
11322 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11326 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11327 // Handle (intptr_t)&&A - (intptr_t)&&B.
11328 if (!LHSVal.getLValueOffset().isZero() ||
11329 !RHSVal.getLValueOffset().isZero())
11331 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11332 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11333 if (!LHSExpr || !RHSExpr)
11335 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11336 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11337 if (!LHSAddrExpr || !RHSAddrExpr)
11339 // Make sure both labels come from the same function.
11340 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11341 RHSAddrExpr->getLabel()->getDeclContext())
11343 Result = APValue(LHSAddrExpr, RHSAddrExpr);
11347 // All the remaining cases expect both operands to be an integer
11348 if (!LHSVal.isInt() || !RHSVal.isInt())
11351 // Set up the width and signedness manually, in case it can't be deduced
11352 // from the operation we're performing.
11353 // FIXME: Don't do this in the cases where we can deduce it.
11354 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11355 E->getType()->isUnsignedIntegerOrEnumerationType());
11356 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11357 RHSVal.getInt(), Value))
11359 return Success(Value, E, Result);
11362 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11363 Job &job = Queue.back();
11365 switch (job.Kind) {
11366 case Job::AnyExprKind: {
11367 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11368 if (shouldEnqueue(Bop)) {
11369 job.Kind = Job::BinOpKind;
11370 enqueue(Bop->getLHS());
11375 EvaluateExpr(job.E, Result);
11380 case Job::BinOpKind: {
11381 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11382 bool SuppressRHSDiags = false;
11383 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11387 if (SuppressRHSDiags)
11388 job.startSpeculativeEval(Info);
11389 job.LHSResult.swap(Result);
11390 job.Kind = Job::BinOpVisitedLHSKind;
11391 enqueue(Bop->getRHS());
11395 case Job::BinOpVisitedLHSKind: {
11396 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11399 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11405 llvm_unreachable("Invalid Job::Kind!");
11409 /// Used when we determine that we should fail, but can keep evaluating prior to
11410 /// noting that we had a failure.
11411 class DelayedNoteFailureRAII {
11416 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11417 : Info(Info), NoteFailure(NoteFailure) {}
11418 ~DelayedNoteFailureRAII() {
11420 bool ContinueAfterFailure = Info.noteFailure();
11421 (void)ContinueAfterFailure;
11422 assert(ContinueAfterFailure &&
11423 "Shouldn't have kept evaluating on failure.");
11429 template <class SuccessCB, class AfterCB>
11431 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11432 SuccessCB &&Success, AfterCB &&DoAfter) {
11433 assert(E->isComparisonOp() && "expected comparison operator");
11434 assert((E->getOpcode() == BO_Cmp ||
11435 E->getType()->isIntegralOrEnumerationType()) &&
11436 "unsupported binary expression evaluation");
11437 auto Error = [&](const Expr *E) {
11438 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11442 using CCR = ComparisonCategoryResult;
11443 bool IsRelational = E->isRelationalOp();
11444 bool IsEquality = E->isEqualityOp();
11445 if (E->getOpcode() == BO_Cmp) {
11446 const ComparisonCategoryInfo &CmpInfo =
11447 Info.Ctx.CompCategories.getInfoForType(E->getType());
11448 IsRelational = CmpInfo.isOrdered();
11449 IsEquality = CmpInfo.isEquality();
11452 QualType LHSTy = E->getLHS()->getType();
11453 QualType RHSTy = E->getRHS()->getType();
11455 if (LHSTy->isIntegralOrEnumerationType() &&
11456 RHSTy->isIntegralOrEnumerationType()) {
11458 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11459 if (!LHSOK && !Info.noteFailure())
11461 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11464 return Success(CCR::Less, E);
11466 return Success(CCR::Greater, E);
11467 return Success(CCR::Equal, E);
11470 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11471 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11472 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11474 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11475 if (!LHSOK && !Info.noteFailure())
11477 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11480 return Success(CCR::Less, E);
11482 return Success(CCR::Greater, E);
11483 return Success(CCR::Equal, E);
11486 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11487 ComplexValue LHS, RHS;
11489 if (E->isAssignmentOp()) {
11491 EvaluateLValue(E->getLHS(), LV, Info);
11493 } else if (LHSTy->isRealFloatingType()) {
11494 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11496 LHS.makeComplexFloat();
11497 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11500 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11502 if (!LHSOK && !Info.noteFailure())
11505 if (E->getRHS()->getType()->isRealFloatingType()) {
11506 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11508 RHS.makeComplexFloat();
11509 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11510 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11513 if (LHS.isComplexFloat()) {
11514 APFloat::cmpResult CR_r =
11515 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11516 APFloat::cmpResult CR_i =
11517 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11518 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11519 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
11521 assert(IsEquality && "invalid complex comparison");
11522 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11523 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11524 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
11528 if (LHSTy->isRealFloatingType() &&
11529 RHSTy->isRealFloatingType()) {
11530 APFloat RHS(0.0), LHS(0.0);
11532 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11533 if (!LHSOK && !Info.noteFailure())
11536 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11539 assert(E->isComparisonOp() && "Invalid binary operator!");
11540 auto GetCmpRes = [&]() {
11541 switch (LHS.compare(RHS)) {
11542 case APFloat::cmpEqual:
11544 case APFloat::cmpLessThan:
11546 case APFloat::cmpGreaterThan:
11547 return CCR::Greater;
11548 case APFloat::cmpUnordered:
11549 return CCR::Unordered;
11551 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11553 return Success(GetCmpRes(), E);
11556 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11557 LValue LHSValue, RHSValue;
11559 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11560 if (!LHSOK && !Info.noteFailure())
11563 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11566 // Reject differing bases from the normal codepath; we special-case
11567 // comparisons to null.
11568 if (!HasSameBase(LHSValue, RHSValue)) {
11569 // Inequalities and subtractions between unrelated pointers have
11570 // unspecified or undefined behavior.
11573 // A constant address may compare equal to the address of a symbol.
11574 // The one exception is that address of an object cannot compare equal
11575 // to a null pointer constant.
11576 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11577 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11579 // It's implementation-defined whether distinct literals will have
11580 // distinct addresses. In clang, the result of such a comparison is
11581 // unspecified, so it is not a constant expression. However, we do know
11582 // that the address of a literal will be non-null.
11583 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11584 LHSValue.Base && RHSValue.Base)
11586 // We can't tell whether weak symbols will end up pointing to the same
11588 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11590 // We can't compare the address of the start of one object with the
11591 // past-the-end address of another object, per C++ DR1652.
11592 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11593 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11594 (RHSValue.Base && RHSValue.Offset.isZero() &&
11595 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11597 // We can't tell whether an object is at the same address as another
11598 // zero sized object.
11599 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11600 (LHSValue.Base && isZeroSized(RHSValue)))
11602 return Success(CCR::Nonequal, E);
11605 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11606 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11608 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11609 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11611 // C++11 [expr.rel]p3:
11612 // Pointers to void (after pointer conversions) can be compared, with a
11613 // result defined as follows: If both pointers represent the same
11614 // address or are both the null pointer value, the result is true if the
11615 // operator is <= or >= and false otherwise; otherwise the result is
11617 // We interpret this as applying to pointers to *cv* void.
11618 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11619 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11621 // C++11 [expr.rel]p2:
11622 // - If two pointers point to non-static data members of the same object,
11623 // or to subobjects or array elements fo such members, recursively, the
11624 // pointer to the later declared member compares greater provided the
11625 // two members have the same access control and provided their class is
11628 // - Otherwise pointer comparisons are unspecified.
11629 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11630 bool WasArrayIndex;
11631 unsigned Mismatch = FindDesignatorMismatch(
11632 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11633 // At the point where the designators diverge, the comparison has a
11634 // specified value if:
11635 // - we are comparing array indices
11636 // - we are comparing fields of a union, or fields with the same access
11637 // Otherwise, the result is unspecified and thus the comparison is not a
11638 // constant expression.
11639 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11640 Mismatch < RHSDesignator.Entries.size()) {
11641 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11642 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11644 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11646 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11647 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11648 << RF->getParent() << RF;
11650 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11651 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11652 << LF->getParent() << LF;
11653 else if (!LF->getParent()->isUnion() &&
11654 LF->getAccess() != RF->getAccess())
11656 diag::note_constexpr_pointer_comparison_differing_access)
11657 << LF << LF->getAccess() << RF << RF->getAccess()
11658 << LF->getParent();
11662 // The comparison here must be unsigned, and performed with the same
11663 // width as the pointer.
11664 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11665 uint64_t CompareLHS = LHSOffset.getQuantity();
11666 uint64_t CompareRHS = RHSOffset.getQuantity();
11667 assert(PtrSize <= 64 && "Unexpected pointer width");
11668 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11669 CompareLHS &= Mask;
11670 CompareRHS &= Mask;
11672 // If there is a base and this is a relational operator, we can only
11673 // compare pointers within the object in question; otherwise, the result
11674 // depends on where the object is located in memory.
11675 if (!LHSValue.Base.isNull() && IsRelational) {
11676 QualType BaseTy = getType(LHSValue.Base);
11677 if (BaseTy->isIncompleteType())
11679 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11680 uint64_t OffsetLimit = Size.getQuantity();
11681 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11685 if (CompareLHS < CompareRHS)
11686 return Success(CCR::Less, E);
11687 if (CompareLHS > CompareRHS)
11688 return Success(CCR::Greater, E);
11689 return Success(CCR::Equal, E);
11692 if (LHSTy->isMemberPointerType()) {
11693 assert(IsEquality && "unexpected member pointer operation");
11694 assert(RHSTy->isMemberPointerType() && "invalid comparison");
11696 MemberPtr LHSValue, RHSValue;
11698 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
11699 if (!LHSOK && !Info.noteFailure())
11702 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11705 // C++11 [expr.eq]p2:
11706 // If both operands are null, they compare equal. Otherwise if only one is
11707 // null, they compare unequal.
11708 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11709 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
11710 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
11713 // Otherwise if either is a pointer to a virtual member function, the
11714 // result is unspecified.
11715 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11716 if (MD->isVirtual())
11717 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11719 if (MD->isVirtual())
11720 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11722 // Otherwise they compare equal if and only if they would refer to the
11723 // same member of the same most derived object or the same subobject if
11724 // they were dereferenced with a hypothetical object of the associated
11726 bool Equal = LHSValue == RHSValue;
11727 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
11730 if (LHSTy->isNullPtrType()) {
11731 assert(E->isComparisonOp() && "unexpected nullptr operation");
11732 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
11733 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11734 // are compared, the result is true of the operator is <=, >= or ==, and
11735 // false otherwise.
11736 return Success(CCR::Equal, E);
11742 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11743 if (!CheckLiteralType(Info, E))
11746 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11747 const BinaryOperator *E) {
11748 // Evaluation succeeded. Lookup the information for the comparison category
11749 // type and fetch the VarDecl for the result.
11750 const ComparisonCategoryInfo &CmpInfo =
11751 Info.Ctx.CompCategories.getInfoForType(E->getType());
11752 const VarDecl *VD =
11753 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11754 // Check and evaluate the result as a constant expression.
11757 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11759 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11761 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11762 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11766 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11767 // We don't call noteFailure immediately because the assignment happens after
11768 // we evaluate LHS and RHS.
11769 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11772 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11773 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11774 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11776 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11777 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
11778 "DataRecursiveIntBinOpEvaluator should have handled integral types");
11780 if (E->isComparisonOp()) {
11781 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11782 // comparisons and then translating the result.
11783 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11784 const BinaryOperator *E) {
11785 using CCR = ComparisonCategoryResult;
11786 bool IsEqual = ResKind == CCR::Equal,
11787 IsLess = ResKind == CCR::Less,
11788 IsGreater = ResKind == CCR::Greater;
11789 auto Op = E->getOpcode();
11792 llvm_unreachable("unsupported binary operator");
11795 return Success(IsEqual == (Op == BO_EQ), E);
11796 case BO_LT: return Success(IsLess, E);
11797 case BO_GT: return Success(IsGreater, E);
11798 case BO_LE: return Success(IsEqual || IsLess, E);
11799 case BO_GE: return Success(IsEqual || IsGreater, E);
11802 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11803 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11807 QualType LHSTy = E->getLHS()->getType();
11808 QualType RHSTy = E->getRHS()->getType();
11810 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11811 E->getOpcode() == BO_Sub) {
11812 LValue LHSValue, RHSValue;
11814 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11815 if (!LHSOK && !Info.noteFailure())
11818 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11821 // Reject differing bases from the normal codepath; we special-case
11822 // comparisons to null.
11823 if (!HasSameBase(LHSValue, RHSValue)) {
11824 // Handle &&A - &&B.
11825 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11827 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11828 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11829 if (!LHSExpr || !RHSExpr)
11831 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11832 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11833 if (!LHSAddrExpr || !RHSAddrExpr)
11835 // Make sure both labels come from the same function.
11836 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11837 RHSAddrExpr->getLabel()->getDeclContext())
11839 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11841 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11842 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11844 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11845 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11847 // C++11 [expr.add]p6:
11848 // Unless both pointers point to elements of the same array object, or
11849 // one past the last element of the array object, the behavior is
11851 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11852 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11854 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11856 QualType Type = E->getLHS()->getType();
11857 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
11859 CharUnits ElementSize;
11860 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11863 // As an extension, a type may have zero size (empty struct or union in
11864 // C, array of zero length). Pointer subtraction in such cases has
11865 // undefined behavior, so is not constant.
11866 if (ElementSize.isZero()) {
11867 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11872 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11873 // and produce incorrect results when it overflows. Such behavior
11874 // appears to be non-conforming, but is common, so perhaps we should
11875 // assume the standard intended for such cases to be undefined behavior
11876 // and check for them.
11878 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11879 // overflow in the final conversion to ptrdiff_t.
11880 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11881 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11882 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11884 APSInt TrueResult = (LHS - RHS) / ElemSize;
11885 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11887 if (Result.extend(65) != TrueResult &&
11888 !HandleOverflow(Info, E, TrueResult, E->getType()))
11890 return Success(Result, E);
11893 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11896 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11897 /// a result as the expression's type.
11898 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11899 const UnaryExprOrTypeTraitExpr *E) {
11900 switch(E->getKind()) {
11901 case UETT_PreferredAlignOf:
11902 case UETT_AlignOf: {
11903 if (E->isArgumentType())
11904 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11907 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11911 case UETT_VecStep: {
11912 QualType Ty = E->getTypeOfArgument();
11914 if (Ty->isVectorType()) {
11915 unsigned n = Ty->castAs<VectorType>()->getNumElements();
11917 // The vec_step built-in functions that take a 3-component
11918 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11922 return Success(n, E);
11924 return Success(1, E);
11927 case UETT_SizeOf: {
11928 QualType SrcTy = E->getTypeOfArgument();
11929 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11930 // the result is the size of the referenced type."
11931 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11932 SrcTy = Ref->getPointeeType();
11935 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
11937 return Success(Sizeof, E);
11939 case UETT_OpenMPRequiredSimdAlign:
11940 assert(E->isArgumentType());
11942 Info.Ctx.toCharUnitsFromBits(
11943 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11948 llvm_unreachable("unknown expr/type trait");
11951 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
11953 unsigned n = OOE->getNumComponents();
11956 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
11957 for (unsigned i = 0; i != n; ++i) {
11958 OffsetOfNode ON = OOE->getComponent(i);
11959 switch (ON.getKind()) {
11960 case OffsetOfNode::Array: {
11961 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
11963 if (!EvaluateInteger(Idx, IdxResult, Info))
11965 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11968 CurrentType = AT->getElementType();
11969 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11970 Result += IdxResult.getSExtValue() * ElementSize;
11974 case OffsetOfNode::Field: {
11975 FieldDecl *MemberDecl = ON.getField();
11976 const RecordType *RT = CurrentType->getAs<RecordType>();
11979 RecordDecl *RD = RT->getDecl();
11980 if (RD->isInvalidDecl()) return false;
11981 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11982 unsigned i = MemberDecl->getFieldIndex();
11983 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
11984 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
11985 CurrentType = MemberDecl->getType().getNonReferenceType();
11989 case OffsetOfNode::Identifier:
11990 llvm_unreachable("dependent __builtin_offsetof");
11992 case OffsetOfNode::Base: {
11993 CXXBaseSpecifier *BaseSpec = ON.getBase();
11994 if (BaseSpec->isVirtual())
11997 // Find the layout of the class whose base we are looking into.
11998 const RecordType *RT = CurrentType->getAs<RecordType>();
12001 RecordDecl *RD = RT->getDecl();
12002 if (RD->isInvalidDecl()) return false;
12003 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12005 // Find the base class itself.
12006 CurrentType = BaseSpec->getType();
12007 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12011 // Add the offset to the base.
12012 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12017 return Success(Result, OOE);
12020 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12021 switch (E->getOpcode()) {
12023 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12027 // FIXME: Should extension allow i-c-e extension expressions in its scope?
12028 // If so, we could clear the diagnostic ID.
12029 return Visit(E->getSubExpr());
12031 // The result is just the value.
12032 return Visit(E->getSubExpr());
12034 if (!Visit(E->getSubExpr()))
12036 if (!Result.isInt()) return Error(E);
12037 const APSInt &Value = Result.getInt();
12038 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12039 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12042 return Success(-Value, E);
12045 if (!Visit(E->getSubExpr()))
12047 if (!Result.isInt()) return Error(E);
12048 return Success(~Result.getInt(), E);
12052 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12054 return Success(!bres, E);
12059 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12060 /// result type is integer.
12061 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12062 const Expr *SubExpr = E->getSubExpr();
12063 QualType DestType = E->getType();
12064 QualType SrcType = SubExpr->getType();
12066 switch (E->getCastKind()) {
12067 case CK_BaseToDerived:
12068 case CK_DerivedToBase:
12069 case CK_UncheckedDerivedToBase:
12072 case CK_ArrayToPointerDecay:
12073 case CK_FunctionToPointerDecay:
12074 case CK_NullToPointer:
12075 case CK_NullToMemberPointer:
12076 case CK_BaseToDerivedMemberPointer:
12077 case CK_DerivedToBaseMemberPointer:
12078 case CK_ReinterpretMemberPointer:
12079 case CK_ConstructorConversion:
12080 case CK_IntegralToPointer:
12082 case CK_VectorSplat:
12083 case CK_IntegralToFloating:
12084 case CK_FloatingCast:
12085 case CK_CPointerToObjCPointerCast:
12086 case CK_BlockPointerToObjCPointerCast:
12087 case CK_AnyPointerToBlockPointerCast:
12088 case CK_ObjCObjectLValueCast:
12089 case CK_FloatingRealToComplex:
12090 case CK_FloatingComplexToReal:
12091 case CK_FloatingComplexCast:
12092 case CK_FloatingComplexToIntegralComplex:
12093 case CK_IntegralRealToComplex:
12094 case CK_IntegralComplexCast:
12095 case CK_IntegralComplexToFloatingComplex:
12096 case CK_BuiltinFnToFnPtr:
12097 case CK_ZeroToOCLOpaqueType:
12098 case CK_NonAtomicToAtomic:
12099 case CK_AddressSpaceConversion:
12100 case CK_IntToOCLSampler:
12101 case CK_FixedPointCast:
12102 case CK_IntegralToFixedPoint:
12103 llvm_unreachable("invalid cast kind for integral value");
12107 case CK_LValueBitCast:
12108 case CK_ARCProduceObject:
12109 case CK_ARCConsumeObject:
12110 case CK_ARCReclaimReturnedObject:
12111 case CK_ARCExtendBlockObject:
12112 case CK_CopyAndAutoreleaseBlockObject:
12115 case CK_UserDefinedConversion:
12116 case CK_LValueToRValue:
12117 case CK_AtomicToNonAtomic:
12119 case CK_LValueToRValueBitCast:
12120 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12122 case CK_MemberPointerToBoolean:
12123 case CK_PointerToBoolean:
12124 case CK_IntegralToBoolean:
12125 case CK_FloatingToBoolean:
12126 case CK_BooleanToSignedIntegral:
12127 case CK_FloatingComplexToBoolean:
12128 case CK_IntegralComplexToBoolean: {
12130 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12132 uint64_t IntResult = BoolResult;
12133 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12134 IntResult = (uint64_t)-1;
12135 return Success(IntResult, E);
12138 case CK_FixedPointToIntegral: {
12139 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12140 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12143 llvm::APSInt Result = Src.convertToInt(
12144 Info.Ctx.getIntWidth(DestType),
12145 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12146 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12148 return Success(Result, E);
12151 case CK_FixedPointToBoolean: {
12152 // Unsigned padding does not affect this.
12154 if (!Evaluate(Val, Info, SubExpr))
12156 return Success(Val.getFixedPoint().getBoolValue(), E);
12159 case CK_IntegralCast: {
12160 if (!Visit(SubExpr))
12163 if (!Result.isInt()) {
12164 // Allow casts of address-of-label differences if they are no-ops
12165 // or narrowing. (The narrowing case isn't actually guaranteed to
12166 // be constant-evaluatable except in some narrow cases which are hard
12167 // to detect here. We let it through on the assumption the user knows
12168 // what they are doing.)
12169 if (Result.isAddrLabelDiff())
12170 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12171 // Only allow casts of lvalues if they are lossless.
12172 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12175 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12176 Result.getInt()), E);
12179 case CK_PointerToIntegral: {
12180 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12183 if (!EvaluatePointer(SubExpr, LV, Info))
12186 if (LV.getLValueBase()) {
12187 // Only allow based lvalue casts if they are lossless.
12188 // FIXME: Allow a larger integer size than the pointer size, and allow
12189 // narrowing back down to pointer width in subsequent integral casts.
12190 // FIXME: Check integer type's active bits, not its type size.
12191 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12194 LV.Designator.setInvalid();
12195 LV.moveInto(Result);
12202 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12203 llvm_unreachable("Can't cast this!");
12205 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12208 case CK_IntegralComplexToReal: {
12210 if (!EvaluateComplex(SubExpr, C, Info))
12212 return Success(C.getComplexIntReal(), E);
12215 case CK_FloatingToIntegral: {
12217 if (!EvaluateFloat(SubExpr, F, Info))
12221 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12223 return Success(Value, E);
12227 llvm_unreachable("unknown cast resulting in integral value");
12230 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12231 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12233 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12235 if (!LV.isComplexInt())
12237 return Success(LV.getComplexIntReal(), E);
12240 return Visit(E->getSubExpr());
12243 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12244 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12246 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12248 if (!LV.isComplexInt())
12250 return Success(LV.getComplexIntImag(), E);
12253 VisitIgnoredValue(E->getSubExpr());
12254 return Success(0, E);
12257 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12258 return Success(E->getPackLength(), E);
12261 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12262 return Success(E->getValue(), E);
12265 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12266 const ConceptSpecializationExpr *E) {
12267 return Success(E->isSatisfied(), E);
12271 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12272 switch (E->getOpcode()) {
12274 // Invalid unary operators
12277 // The result is just the value.
12278 return Visit(E->getSubExpr());
12280 if (!Visit(E->getSubExpr())) return false;
12281 if (!Result.isFixedPoint())
12284 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12285 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12287 return Success(Negated, E);
12291 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12293 return Success(!bres, E);
12298 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12299 const Expr *SubExpr = E->getSubExpr();
12300 QualType DestType = E->getType();
12301 assert(DestType->isFixedPointType() &&
12302 "Expected destination type to be a fixed point type");
12303 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12305 switch (E->getCastKind()) {
12306 case CK_FixedPointCast: {
12307 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12308 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12311 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12312 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12314 return Success(Result, E);
12316 case CK_IntegralToFixedPoint: {
12318 if (!EvaluateInteger(SubExpr, Src, Info))
12322 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12323 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12325 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12328 return Success(IntResult, E);
12331 case CK_LValueToRValue:
12332 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12338 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12339 const Expr *LHS = E->getLHS();
12340 const Expr *RHS = E->getRHS();
12341 FixedPointSemantics ResultFXSema =
12342 Info.Ctx.getFixedPointSemantics(E->getType());
12344 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12345 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12347 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12348 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12351 switch (E->getOpcode()) {
12353 bool AddOverflow, ConversionOverflow;
12354 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12355 .convert(ResultFXSema, &ConversionOverflow);
12356 if ((AddOverflow || ConversionOverflow) &&
12357 !HandleOverflow(Info, E, Result, E->getType()))
12359 return Success(Result, E);
12364 llvm_unreachable("Should've exited before this");
12367 //===----------------------------------------------------------------------===//
12368 // Float Evaluation
12369 //===----------------------------------------------------------------------===//
12372 class FloatExprEvaluator
12373 : public ExprEvaluatorBase<FloatExprEvaluator> {
12376 FloatExprEvaluator(EvalInfo &info, APFloat &result)
12377 : ExprEvaluatorBaseTy(info), Result(result) {}
12379 bool Success(const APValue &V, const Expr *e) {
12380 Result = V.getFloat();
12384 bool ZeroInitialization(const Expr *E) {
12385 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12389 bool VisitCallExpr(const CallExpr *E);
12391 bool VisitUnaryOperator(const UnaryOperator *E);
12392 bool VisitBinaryOperator(const BinaryOperator *E);
12393 bool VisitFloatingLiteral(const FloatingLiteral *E);
12394 bool VisitCastExpr(const CastExpr *E);
12396 bool VisitUnaryReal(const UnaryOperator *E);
12397 bool VisitUnaryImag(const UnaryOperator *E);
12399 // FIXME: Missing: array subscript of vector, member of vector
12401 } // end anonymous namespace
12403 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12404 assert(E->isRValue() && E->getType()->isRealFloatingType());
12405 return FloatExprEvaluator(Info, Result).Visit(E);
12408 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12412 llvm::APFloat &Result) {
12413 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12414 if (!S) return false;
12416 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12420 // Treat empty strings as if they were zero.
12421 if (S->getString().empty())
12422 fill = llvm::APInt(32, 0);
12423 else if (S->getString().getAsInteger(0, fill))
12426 if (Context.getTargetInfo().isNan2008()) {
12428 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12430 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12432 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12433 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12434 // a different encoding to what became a standard in 2008, and for pre-
12435 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12436 // sNaN. This is now known as "legacy NaN" encoding.
12438 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12440 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12446 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12447 switch (E->getBuiltinCallee()) {
12449 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12451 case Builtin::BI__builtin_huge_val:
12452 case Builtin::BI__builtin_huge_valf:
12453 case Builtin::BI__builtin_huge_vall:
12454 case Builtin::BI__builtin_huge_valf128:
12455 case Builtin::BI__builtin_inf:
12456 case Builtin::BI__builtin_inff:
12457 case Builtin::BI__builtin_infl:
12458 case Builtin::BI__builtin_inff128: {
12459 const llvm::fltSemantics &Sem =
12460 Info.Ctx.getFloatTypeSemantics(E->getType());
12461 Result = llvm::APFloat::getInf(Sem);
12465 case Builtin::BI__builtin_nans:
12466 case Builtin::BI__builtin_nansf:
12467 case Builtin::BI__builtin_nansl:
12468 case Builtin::BI__builtin_nansf128:
12469 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12474 case Builtin::BI__builtin_nan:
12475 case Builtin::BI__builtin_nanf:
12476 case Builtin::BI__builtin_nanl:
12477 case Builtin::BI__builtin_nanf128:
12478 // If this is __builtin_nan() turn this into a nan, otherwise we
12479 // can't constant fold it.
12480 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12485 case Builtin::BI__builtin_fabs:
12486 case Builtin::BI__builtin_fabsf:
12487 case Builtin::BI__builtin_fabsl:
12488 case Builtin::BI__builtin_fabsf128:
12489 if (!EvaluateFloat(E->getArg(0), Result, Info))
12492 if (Result.isNegative())
12493 Result.changeSign();
12496 // FIXME: Builtin::BI__builtin_powi
12497 // FIXME: Builtin::BI__builtin_powif
12498 // FIXME: Builtin::BI__builtin_powil
12500 case Builtin::BI__builtin_copysign:
12501 case Builtin::BI__builtin_copysignf:
12502 case Builtin::BI__builtin_copysignl:
12503 case Builtin::BI__builtin_copysignf128: {
12505 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12506 !EvaluateFloat(E->getArg(1), RHS, Info))
12508 Result.copySign(RHS);
12514 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12515 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12517 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12519 Result = CV.FloatReal;
12523 return Visit(E->getSubExpr());
12526 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12527 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12529 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12531 Result = CV.FloatImag;
12535 VisitIgnoredValue(E->getSubExpr());
12536 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12537 Result = llvm::APFloat::getZero(Sem);
12541 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12542 switch (E->getOpcode()) {
12543 default: return Error(E);
12545 return EvaluateFloat(E->getSubExpr(), Result, Info);
12547 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12549 Result.changeSign();
12554 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12555 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12556 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12559 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12560 if (!LHSOK && !Info.noteFailure())
12562 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12563 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12566 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12567 Result = E->getValue();
12571 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12572 const Expr* SubExpr = E->getSubExpr();
12574 switch (E->getCastKind()) {
12576 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12578 case CK_IntegralToFloating: {
12580 return EvaluateInteger(SubExpr, IntResult, Info) &&
12581 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12582 E->getType(), Result);
12585 case CK_FloatingCast: {
12586 if (!Visit(SubExpr))
12588 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12592 case CK_FloatingComplexToReal: {
12594 if (!EvaluateComplex(SubExpr, V, Info))
12596 Result = V.getComplexFloatReal();
12602 //===----------------------------------------------------------------------===//
12603 // Complex Evaluation (for float and integer)
12604 //===----------------------------------------------------------------------===//
12607 class ComplexExprEvaluator
12608 : public ExprEvaluatorBase<ComplexExprEvaluator> {
12609 ComplexValue &Result;
12612 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12613 : ExprEvaluatorBaseTy(info), Result(Result) {}
12615 bool Success(const APValue &V, const Expr *e) {
12620 bool ZeroInitialization(const Expr *E);
12622 //===--------------------------------------------------------------------===//
12624 //===--------------------------------------------------------------------===//
12626 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12627 bool VisitCastExpr(const CastExpr *E);
12628 bool VisitBinaryOperator(const BinaryOperator *E);
12629 bool VisitUnaryOperator(const UnaryOperator *E);
12630 bool VisitInitListExpr(const InitListExpr *E);
12632 } // end anonymous namespace
12634 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12636 assert(E->isRValue() && E->getType()->isAnyComplexType());
12637 return ComplexExprEvaluator(Info, Result).Visit(E);
12640 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12641 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12642 if (ElemTy->isRealFloatingType()) {
12643 Result.makeComplexFloat();
12644 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12645 Result.FloatReal = Zero;
12646 Result.FloatImag = Zero;
12648 Result.makeComplexInt();
12649 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12650 Result.IntReal = Zero;
12651 Result.IntImag = Zero;
12656 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12657 const Expr* SubExpr = E->getSubExpr();
12659 if (SubExpr->getType()->isRealFloatingType()) {
12660 Result.makeComplexFloat();
12661 APFloat &Imag = Result.FloatImag;
12662 if (!EvaluateFloat(SubExpr, Imag, Info))
12665 Result.FloatReal = APFloat(Imag.getSemantics());
12668 assert(SubExpr->getType()->isIntegerType() &&
12669 "Unexpected imaginary literal.");
12671 Result.makeComplexInt();
12672 APSInt &Imag = Result.IntImag;
12673 if (!EvaluateInteger(SubExpr, Imag, Info))
12676 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12681 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
12683 switch (E->getCastKind()) {
12685 case CK_BaseToDerived:
12686 case CK_DerivedToBase:
12687 case CK_UncheckedDerivedToBase:
12690 case CK_ArrayToPointerDecay:
12691 case CK_FunctionToPointerDecay:
12692 case CK_NullToPointer:
12693 case CK_NullToMemberPointer:
12694 case CK_BaseToDerivedMemberPointer:
12695 case CK_DerivedToBaseMemberPointer:
12696 case CK_MemberPointerToBoolean:
12697 case CK_ReinterpretMemberPointer:
12698 case CK_ConstructorConversion:
12699 case CK_IntegralToPointer:
12700 case CK_PointerToIntegral:
12701 case CK_PointerToBoolean:
12703 case CK_VectorSplat:
12704 case CK_IntegralCast:
12705 case CK_BooleanToSignedIntegral:
12706 case CK_IntegralToBoolean:
12707 case CK_IntegralToFloating:
12708 case CK_FloatingToIntegral:
12709 case CK_FloatingToBoolean:
12710 case CK_FloatingCast:
12711 case CK_CPointerToObjCPointerCast:
12712 case CK_BlockPointerToObjCPointerCast:
12713 case CK_AnyPointerToBlockPointerCast:
12714 case CK_ObjCObjectLValueCast:
12715 case CK_FloatingComplexToReal:
12716 case CK_FloatingComplexToBoolean:
12717 case CK_IntegralComplexToReal:
12718 case CK_IntegralComplexToBoolean:
12719 case CK_ARCProduceObject:
12720 case CK_ARCConsumeObject:
12721 case CK_ARCReclaimReturnedObject:
12722 case CK_ARCExtendBlockObject:
12723 case CK_CopyAndAutoreleaseBlockObject:
12724 case CK_BuiltinFnToFnPtr:
12725 case CK_ZeroToOCLOpaqueType:
12726 case CK_NonAtomicToAtomic:
12727 case CK_AddressSpaceConversion:
12728 case CK_IntToOCLSampler:
12729 case CK_FixedPointCast:
12730 case CK_FixedPointToBoolean:
12731 case CK_FixedPointToIntegral:
12732 case CK_IntegralToFixedPoint:
12733 llvm_unreachable("invalid cast kind for complex value");
12735 case CK_LValueToRValue:
12736 case CK_AtomicToNonAtomic:
12738 case CK_LValueToRValueBitCast:
12739 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12742 case CK_LValueBitCast:
12743 case CK_UserDefinedConversion:
12746 case CK_FloatingRealToComplex: {
12747 APFloat &Real = Result.FloatReal;
12748 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
12751 Result.makeComplexFloat();
12752 Result.FloatImag = APFloat(Real.getSemantics());
12756 case CK_FloatingComplexCast: {
12757 if (!Visit(E->getSubExpr()))
12760 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
12762 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
12764 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12765 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
12768 case CK_FloatingComplexToIntegralComplex: {
12769 if (!Visit(E->getSubExpr()))
12772 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
12774 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
12775 Result.makeComplexInt();
12776 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12777 To, Result.IntReal) &&
12778 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12779 To, Result.IntImag);
12782 case CK_IntegralRealToComplex: {
12783 APSInt &Real = Result.IntReal;
12784 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12787 Result.makeComplexInt();
12788 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12792 case CK_IntegralComplexCast: {
12793 if (!Visit(E->getSubExpr()))
12796 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
12798 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
12800 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12801 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
12805 case CK_IntegralComplexToFloatingComplex: {
12806 if (!Visit(E->getSubExpr()))
12809 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
12811 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
12812 Result.makeComplexFloat();
12813 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12814 To, Result.FloatReal) &&
12815 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12816 To, Result.FloatImag);
12820 llvm_unreachable("unknown cast resulting in complex value");
12823 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12824 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12825 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12827 // Track whether the LHS or RHS is real at the type system level. When this is
12828 // the case we can simplify our evaluation strategy.
12829 bool LHSReal = false, RHSReal = false;
12832 if (E->getLHS()->getType()->isRealFloatingType()) {
12834 APFloat &Real = Result.FloatReal;
12835 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12837 Result.makeComplexFloat();
12838 Result.FloatImag = APFloat(Real.getSemantics());
12841 LHSOK = Visit(E->getLHS());
12843 if (!LHSOK && !Info.noteFailure())
12847 if (E->getRHS()->getType()->isRealFloatingType()) {
12849 APFloat &Real = RHS.FloatReal;
12850 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12852 RHS.makeComplexFloat();
12853 RHS.FloatImag = APFloat(Real.getSemantics());
12854 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12857 assert(!(LHSReal && RHSReal) &&
12858 "Cannot have both operands of a complex operation be real.");
12859 switch (E->getOpcode()) {
12860 default: return Error(E);
12862 if (Result.isComplexFloat()) {
12863 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12864 APFloat::rmNearestTiesToEven);
12866 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12868 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12869 APFloat::rmNearestTiesToEven);
12871 Result.getComplexIntReal() += RHS.getComplexIntReal();
12872 Result.getComplexIntImag() += RHS.getComplexIntImag();
12876 if (Result.isComplexFloat()) {
12877 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12878 APFloat::rmNearestTiesToEven);
12880 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12881 Result.getComplexFloatImag().changeSign();
12882 } else if (!RHSReal) {
12883 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12884 APFloat::rmNearestTiesToEven);
12887 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12888 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12892 if (Result.isComplexFloat()) {
12893 // This is an implementation of complex multiplication according to the
12894 // constraints laid out in C11 Annex G. The implementation uses the
12895 // following naming scheme:
12896 // (a + ib) * (c + id)
12897 ComplexValue LHS = Result;
12898 APFloat &A = LHS.getComplexFloatReal();
12899 APFloat &B = LHS.getComplexFloatImag();
12900 APFloat &C = RHS.getComplexFloatReal();
12901 APFloat &D = RHS.getComplexFloatImag();
12902 APFloat &ResR = Result.getComplexFloatReal();
12903 APFloat &ResI = Result.getComplexFloatImag();
12905 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12908 } else if (RHSReal) {
12912 // In the fully general case, we need to handle NaNs and infinities
12914 APFloat AC = A * C;
12915 APFloat BD = B * D;
12916 APFloat AD = A * D;
12917 APFloat BC = B * C;
12920 if (ResR.isNaN() && ResI.isNaN()) {
12921 bool Recalc = false;
12922 if (A.isInfinity() || B.isInfinity()) {
12923 A = APFloat::copySign(
12924 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12925 B = APFloat::copySign(
12926 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12928 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12930 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12933 if (C.isInfinity() || D.isInfinity()) {
12934 C = APFloat::copySign(
12935 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12936 D = APFloat::copySign(
12937 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12939 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12941 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12944 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12945 AD.isInfinity() || BC.isInfinity())) {
12947 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12949 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12951 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12953 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12957 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12958 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12963 ComplexValue LHS = Result;
12964 Result.getComplexIntReal() =
12965 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12966 LHS.getComplexIntImag() * RHS.getComplexIntImag());
12967 Result.getComplexIntImag() =
12968 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12969 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12973 if (Result.isComplexFloat()) {
12974 // This is an implementation of complex division according to the
12975 // constraints laid out in C11 Annex G. The implementation uses the
12976 // following naming scheme:
12977 // (a + ib) / (c + id)
12978 ComplexValue LHS = Result;
12979 APFloat &A = LHS.getComplexFloatReal();
12980 APFloat &B = LHS.getComplexFloatImag();
12981 APFloat &C = RHS.getComplexFloatReal();
12982 APFloat &D = RHS.getComplexFloatImag();
12983 APFloat &ResR = Result.getComplexFloatReal();
12984 APFloat &ResI = Result.getComplexFloatImag();
12990 // No real optimizations we can do here, stub out with zero.
12991 B = APFloat::getZero(A.getSemantics());
12994 APFloat MaxCD = maxnum(abs(C), abs(D));
12995 if (MaxCD.isFinite()) {
12996 DenomLogB = ilogb(MaxCD);
12997 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12998 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13000 APFloat Denom = C * C + D * D;
13001 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13002 APFloat::rmNearestTiesToEven);
13003 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13004 APFloat::rmNearestTiesToEven);
13005 if (ResR.isNaN() && ResI.isNaN()) {
13006 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13007 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13008 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13009 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13011 A = APFloat::copySign(
13012 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13013 B = APFloat::copySign(
13014 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13015 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13016 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13017 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13018 C = APFloat::copySign(
13019 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13020 D = APFloat::copySign(
13021 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13022 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13023 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13028 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13029 return Error(E, diag::note_expr_divide_by_zero);
13031 ComplexValue LHS = Result;
13032 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13033 RHS.getComplexIntImag() * RHS.getComplexIntImag();
13034 Result.getComplexIntReal() =
13035 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13036 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13037 Result.getComplexIntImag() =
13038 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13039 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13047 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13048 // Get the operand value into 'Result'.
13049 if (!Visit(E->getSubExpr()))
13052 switch (E->getOpcode()) {
13058 // The result is always just the subexpr.
13061 if (Result.isComplexFloat()) {
13062 Result.getComplexFloatReal().changeSign();
13063 Result.getComplexFloatImag().changeSign();
13066 Result.getComplexIntReal() = -Result.getComplexIntReal();
13067 Result.getComplexIntImag() = -Result.getComplexIntImag();
13071 if (Result.isComplexFloat())
13072 Result.getComplexFloatImag().changeSign();
13074 Result.getComplexIntImag() = -Result.getComplexIntImag();
13079 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13080 if (E->getNumInits() == 2) {
13081 if (E->getType()->isComplexType()) {
13082 Result.makeComplexFloat();
13083 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13085 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13088 Result.makeComplexInt();
13089 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13091 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13096 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13099 //===----------------------------------------------------------------------===//
13100 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13101 // implicit conversion.
13102 //===----------------------------------------------------------------------===//
13105 class AtomicExprEvaluator :
13106 public ExprEvaluatorBase<AtomicExprEvaluator> {
13107 const LValue *This;
13110 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13111 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13113 bool Success(const APValue &V, const Expr *E) {
13118 bool ZeroInitialization(const Expr *E) {
13119 ImplicitValueInitExpr VIE(
13120 E->getType()->castAs<AtomicType>()->getValueType());
13121 // For atomic-qualified class (and array) types in C++, initialize the
13122 // _Atomic-wrapped subobject directly, in-place.
13123 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13124 : Evaluate(Result, Info, &VIE);
13127 bool VisitCastExpr(const CastExpr *E) {
13128 switch (E->getCastKind()) {
13130 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13131 case CK_NonAtomicToAtomic:
13132 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13133 : Evaluate(Result, Info, E->getSubExpr());
13137 } // end anonymous namespace
13139 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13141 assert(E->isRValue() && E->getType()->isAtomicType());
13142 return AtomicExprEvaluator(Info, This, Result).Visit(E);
13145 //===----------------------------------------------------------------------===//
13146 // Void expression evaluation, primarily for a cast to void on the LHS of a
13148 //===----------------------------------------------------------------------===//
13151 class VoidExprEvaluator
13152 : public ExprEvaluatorBase<VoidExprEvaluator> {
13154 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13156 bool Success(const APValue &V, const Expr *e) { return true; }
13158 bool ZeroInitialization(const Expr *E) { return true; }
13160 bool VisitCastExpr(const CastExpr *E) {
13161 switch (E->getCastKind()) {
13163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13165 VisitIgnoredValue(E->getSubExpr());
13170 bool VisitCallExpr(const CallExpr *E) {
13171 switch (E->getBuiltinCallee()) {
13172 case Builtin::BI__assume:
13173 case Builtin::BI__builtin_assume:
13174 // The argument is not evaluated!
13177 case Builtin::BI__builtin_operator_delete:
13178 return HandleOperatorDeleteCall(Info, E);
13184 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13187 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13189 } // end anonymous namespace
13191 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13192 // We cannot speculatively evaluate a delete expression.
13193 if (Info.SpeculativeEvaluationDepth)
13196 FunctionDecl *OperatorDelete = E->getOperatorDelete();
13197 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13198 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13199 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13203 const Expr *Arg = E->getArgument();
13206 if (!EvaluatePointer(Arg, Pointer, Info))
13208 if (Pointer.Designator.Invalid)
13211 // Deleting a null pointer has no effect.
13212 if (Pointer.isNullPointer()) {
13213 // This is the only case where we need to produce an extension warning:
13214 // the only other way we can succeed is if we find a dynamic allocation,
13215 // and we will have warned when we allocated it in that case.
13216 if (!Info.getLangOpts().CPlusPlus2a)
13217 Info.CCEDiag(E, diag::note_constexpr_new);
13221 Optional<DynAlloc *> Alloc = CheckDeleteKind(
13222 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13225 QualType AllocType = Pointer.Base.getDynamicAllocType();
13227 // For the non-array case, the designator must be empty if the static type
13228 // does not have a virtual destructor.
13229 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13230 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13231 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13232 << Arg->getType()->getPointeeType() << AllocType;
13236 // For a class type with a virtual destructor, the selected operator delete
13237 // is the one looked up when building the destructor.
13238 if (!E->isArrayForm() && !E->isGlobalDelete()) {
13239 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13240 if (VirtualDelete &&
13241 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13242 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13243 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13248 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13249 (*Alloc)->Value, AllocType))
13252 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13253 // The element was already erased. This means the destructor call also
13254 // deleted the object.
13255 // FIXME: This probably results in undefined behavior before we get this
13256 // far, and should be diagnosed elsewhere first.
13257 Info.FFDiag(E, diag::note_constexpr_double_delete);
13264 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13265 assert(E->isRValue() && E->getType()->isVoidType());
13266 return VoidExprEvaluator(Info).Visit(E);
13269 //===----------------------------------------------------------------------===//
13270 // Top level Expr::EvaluateAsRValue method.
13271 //===----------------------------------------------------------------------===//
13273 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13274 // In C, function designators are not lvalues, but we evaluate them as if they
13276 QualType T = E->getType();
13277 if (E->isGLValue() || T->isFunctionType()) {
13279 if (!EvaluateLValue(E, LV, Info))
13281 LV.moveInto(Result);
13282 } else if (T->isVectorType()) {
13283 if (!EvaluateVector(E, Result, Info))
13285 } else if (T->isIntegralOrEnumerationType()) {
13286 if (!IntExprEvaluator(Info, Result).Visit(E))
13288 } else if (T->hasPointerRepresentation()) {
13290 if (!EvaluatePointer(E, LV, Info))
13292 LV.moveInto(Result);
13293 } else if (T->isRealFloatingType()) {
13294 llvm::APFloat F(0.0);
13295 if (!EvaluateFloat(E, F, Info))
13297 Result = APValue(F);
13298 } else if (T->isAnyComplexType()) {
13300 if (!EvaluateComplex(E, C, Info))
13302 C.moveInto(Result);
13303 } else if (T->isFixedPointType()) {
13304 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13305 } else if (T->isMemberPointerType()) {
13307 if (!EvaluateMemberPointer(E, P, Info))
13309 P.moveInto(Result);
13311 } else if (T->isArrayType()) {
13314 Info.CurrentCall->createTemporary(E, T, false, LV);
13315 if (!EvaluateArray(E, LV, Value, Info))
13318 } else if (T->isRecordType()) {
13320 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13321 if (!EvaluateRecord(E, LV, Value, Info))
13324 } else if (T->isVoidType()) {
13325 if (!Info.getLangOpts().CPlusPlus11)
13326 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13328 if (!EvaluateVoid(E, Info))
13330 } else if (T->isAtomicType()) {
13331 QualType Unqual = T.getAtomicUnqualifiedType();
13332 if (Unqual->isArrayType() || Unqual->isRecordType()) {
13334 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13335 if (!EvaluateAtomic(E, &LV, Value, Info))
13338 if (!EvaluateAtomic(E, nullptr, Result, Info))
13341 } else if (Info.getLangOpts().CPlusPlus11) {
13342 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13345 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13352 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13353 /// cases, the in-place evaluation is essential, since later initializers for
13354 /// an object can indirectly refer to subobjects which were initialized earlier.
13355 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13356 const Expr *E, bool AllowNonLiteralTypes) {
13357 assert(!E->isValueDependent());
13359 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13362 if (E->isRValue()) {
13363 // Evaluate arrays and record types in-place, so that later initializers can
13364 // refer to earlier-initialized members of the object.
13365 QualType T = E->getType();
13366 if (T->isArrayType())
13367 return EvaluateArray(E, This, Result, Info);
13368 else if (T->isRecordType())
13369 return EvaluateRecord(E, This, Result, Info);
13370 else if (T->isAtomicType()) {
13371 QualType Unqual = T.getAtomicUnqualifiedType();
13372 if (Unqual->isArrayType() || Unqual->isRecordType())
13373 return EvaluateAtomic(E, &This, Result, Info);
13377 // For any other type, in-place evaluation is unimportant.
13378 return Evaluate(Result, Info, E);
13381 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13382 /// lvalue-to-rvalue cast if it is an lvalue.
13383 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13384 if (Info.EnableNewConstInterp) {
13385 auto &InterpCtx = Info.Ctx.getInterpContext();
13386 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
13387 case interp::InterpResult::Success:
13389 case interp::InterpResult::Fail:
13391 case interp::InterpResult::Bail:
13396 if (E->getType().isNull())
13399 if (!CheckLiteralType(Info, E))
13402 if (!::Evaluate(Result, Info, E))
13405 if (E->isGLValue()) {
13407 LV.setFrom(Info.Ctx, Result);
13408 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13412 // Check this core constant expression is a constant expression.
13413 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13414 CheckMemoryLeaks(Info);
13417 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13418 const ASTContext &Ctx, bool &IsConst) {
13419 // Fast-path evaluations of integer literals, since we sometimes see files
13420 // containing vast quantities of these.
13421 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13422 Result.Val = APValue(APSInt(L->getValue(),
13423 L->getType()->isUnsignedIntegerType()));
13428 // This case should be rare, but we need to check it before we check on
13430 if (Exp->getType().isNull()) {
13435 // FIXME: Evaluating values of large array and record types can cause
13436 // performance problems. Only do so in C++11 for now.
13437 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13438 Exp->getType()->isRecordType()) &&
13439 !Ctx.getLangOpts().CPlusPlus11) {
13446 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13447 Expr::SideEffectsKind SEK) {
13448 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13449 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13452 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13453 const ASTContext &Ctx, EvalInfo &Info) {
13455 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13458 return EvaluateAsRValue(Info, E, Result.Val);
13461 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13462 const ASTContext &Ctx,
13463 Expr::SideEffectsKind AllowSideEffects,
13465 if (!E->getType()->isIntegralOrEnumerationType())
13468 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13469 !ExprResult.Val.isInt() ||
13470 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13476 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13477 const ASTContext &Ctx,
13478 Expr::SideEffectsKind AllowSideEffects,
13480 if (!E->getType()->isFixedPointType())
13483 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13486 if (!ExprResult.Val.isFixedPoint() ||
13487 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13493 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13494 /// any crazy technique (that has nothing to do with language standards) that
13495 /// we want to. If this function returns true, it returns the folded constant
13496 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13497 /// will be applied to the result.
13498 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13499 bool InConstantContext) const {
13500 assert(!isValueDependent() &&
13501 "Expression evaluator can't be called on a dependent expression.");
13502 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13503 Info.InConstantContext = InConstantContext;
13504 return ::EvaluateAsRValue(this, Result, Ctx, Info);
13507 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13508 bool InConstantContext) const {
13509 assert(!isValueDependent() &&
13510 "Expression evaluator can't be called on a dependent expression.");
13511 EvalResult Scratch;
13512 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13513 HandleConversionToBool(Scratch.Val, Result);
13516 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13517 SideEffectsKind AllowSideEffects,
13518 bool InConstantContext) const {
13519 assert(!isValueDependent() &&
13520 "Expression evaluator can't be called on a dependent expression.");
13521 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13522 Info.InConstantContext = InConstantContext;
13523 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13526 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13527 SideEffectsKind AllowSideEffects,
13528 bool InConstantContext) const {
13529 assert(!isValueDependent() &&
13530 "Expression evaluator can't be called on a dependent expression.");
13531 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13532 Info.InConstantContext = InConstantContext;
13533 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13536 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13537 SideEffectsKind AllowSideEffects,
13538 bool InConstantContext) const {
13539 assert(!isValueDependent() &&
13540 "Expression evaluator can't be called on a dependent expression.");
13542 if (!getType()->isRealFloatingType())
13545 EvalResult ExprResult;
13546 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13547 !ExprResult.Val.isFloat() ||
13548 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13551 Result = ExprResult.Val.getFloat();
13555 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13556 bool InConstantContext) const {
13557 assert(!isValueDependent() &&
13558 "Expression evaluator can't be called on a dependent expression.");
13560 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13561 Info.InConstantContext = InConstantContext;
13563 CheckedTemporaries CheckedTemps;
13564 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13565 Result.HasSideEffects ||
13566 !CheckLValueConstantExpression(Info, getExprLoc(),
13567 Ctx.getLValueReferenceType(getType()), LV,
13568 Expr::EvaluateForCodeGen, CheckedTemps))
13571 LV.moveInto(Result.Val);
13575 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13576 const ASTContext &Ctx) const {
13577 assert(!isValueDependent() &&
13578 "Expression evaluator can't be called on a dependent expression.");
13580 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13581 EvalInfo Info(Ctx, Result, EM);
13582 Info.InConstantContext = true;
13584 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13587 if (!Info.discardCleanups())
13588 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13590 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13591 Result.Val, Usage) &&
13592 CheckMemoryLeaks(Info);
13595 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13597 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13598 assert(!isValueDependent() &&
13599 "Expression evaluator can't be called on a dependent expression.");
13601 // FIXME: Evaluating initializers for large array and record types can cause
13602 // performance problems. Only do so in C++11 for now.
13603 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13604 !Ctx.getLangOpts().CPlusPlus11)
13607 Expr::EvalStatus EStatus;
13608 EStatus.Diag = &Notes;
13610 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13611 ? EvalInfo::EM_ConstantExpression
13612 : EvalInfo::EM_ConstantFold);
13613 Info.setEvaluatingDecl(VD, Value);
13614 Info.InConstantContext = true;
13616 SourceLocation DeclLoc = VD->getLocation();
13617 QualType DeclTy = VD->getType();
13619 if (Info.EnableNewConstInterp) {
13620 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13621 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
13622 case interp::InterpResult::Fail:
13623 // Bail out if an error was encountered.
13625 case interp::InterpResult::Success:
13626 // Evaluation succeeded and value was set.
13627 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
13628 case interp::InterpResult::Bail:
13629 // Evaluate the value again for the tree evaluator to use.
13637 // C++11 [basic.start.init]p2:
13638 // Variables with static storage duration or thread storage duration shall be
13639 // zero-initialized before any other initialization takes place.
13640 // This behavior is not present in C.
13641 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
13642 !DeclTy->isReferenceType()) {
13643 ImplicitValueInitExpr VIE(DeclTy);
13644 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
13645 /*AllowNonLiteralTypes=*/true))
13649 if (!EvaluateInPlace(Value, Info, LVal, this,
13650 /*AllowNonLiteralTypes=*/true) ||
13651 EStatus.HasSideEffects)
13654 // At this point, any lifetime-extended temporaries are completely
13656 Info.performLifetimeExtension();
13658 if (!Info.discardCleanups())
13659 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13661 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13662 CheckMemoryLeaks(Info);
13665 bool VarDecl::evaluateDestruction(
13666 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13667 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
13668 "cannot evaluate destruction of non-constant-initialized variable");
13670 Expr::EvalStatus EStatus;
13671 EStatus.Diag = &Notes;
13673 // Make a copy of the value for the destructor to mutate.
13674 APValue DestroyedValue = *getEvaluatedValue();
13676 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13677 Info.setEvaluatingDecl(this, DestroyedValue,
13678 EvalInfo::EvaluatingDeclKind::Dtor);
13679 Info.InConstantContext = true;
13681 SourceLocation DeclLoc = getLocation();
13682 QualType DeclTy = getType();
13687 // FIXME: Consider storing whether this variable has constant destruction in
13688 // the EvaluatedStmt so that CodeGen can query it.
13689 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13690 EStatus.HasSideEffects)
13693 if (!Info.discardCleanups())
13694 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13696 ensureEvaluatedStmt()->HasConstantDestruction = true;
13700 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13701 /// constant folded, but discard the result.
13702 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
13703 assert(!isValueDependent() &&
13704 "Expression evaluator can't be called on a dependent expression.");
13707 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
13708 !hasUnacceptableSideEffect(Result, SEK);
13711 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
13712 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13713 assert(!isValueDependent() &&
13714 "Expression evaluator can't be called on a dependent expression.");
13716 EvalResult EVResult;
13717 EVResult.Diag = Diag;
13718 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13719 Info.InConstantContext = true;
13721 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
13723 assert(Result && "Could not evaluate expression");
13724 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
13726 return EVResult.Val.getInt();
13729 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13730 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13731 assert(!isValueDependent() &&
13732 "Expression evaluator can't be called on a dependent expression.");
13734 EvalResult EVResult;
13735 EVResult.Diag = Diag;
13736 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13737 Info.InConstantContext = true;
13738 Info.CheckingForUndefinedBehavior = true;
13740 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
13742 assert(Result && "Could not evaluate expression");
13743 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
13745 return EVResult.Val.getInt();
13748 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
13749 assert(!isValueDependent() &&
13750 "Expression evaluator can't be called on a dependent expression.");
13753 EvalResult EVResult;
13754 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
13755 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13756 Info.CheckingForUndefinedBehavior = true;
13757 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
13761 bool Expr::EvalResult::isGlobalLValue() const {
13762 assert(Val.isLValue());
13763 return IsGlobalLValue(Val.getLValueBase());
13767 /// isIntegerConstantExpr - this recursive routine will test if an expression is
13768 /// an integer constant expression.
13770 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13773 // CheckICE - This function does the fundamental ICE checking: the returned
13774 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13775 // and a (possibly null) SourceLocation indicating the location of the problem.
13777 // Note that to reduce code duplication, this helper does no evaluation
13778 // itself; the caller checks whether the expression is evaluatable, and
13779 // in the rare cases where CheckICE actually cares about the evaluated
13780 // value, it calls into Evaluate.
13785 /// This expression is an ICE.
13787 /// This expression is not an ICE, but if it isn't evaluated, it's
13788 /// a legal subexpression for an ICE. This return value is used to handle
13789 /// the comma operator in C99 mode, and non-constant subexpressions.
13790 IK_ICEIfUnevaluated,
13791 /// This expression is not an ICE, and is not a legal subexpression for one.
13797 SourceLocation Loc;
13799 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
13804 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13806 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
13808 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
13809 Expr::EvalResult EVResult;
13810 Expr::EvalStatus Status;
13811 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13813 Info.InConstantContext = true;
13814 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
13815 !EVResult.Val.isInt())
13816 return ICEDiag(IK_NotICE, E->getBeginLoc());
13821 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
13822 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
13823 if (!E->getType()->isIntegralOrEnumerationType())
13824 return ICEDiag(IK_NotICE, E->getBeginLoc());
13826 switch (E->getStmtClass()) {
13827 #define ABSTRACT_STMT(Node)
13828 #define STMT(Node, Base) case Expr::Node##Class:
13829 #define EXPR(Node, Base)
13830 #include "clang/AST/StmtNodes.inc"
13831 case Expr::PredefinedExprClass:
13832 case Expr::FloatingLiteralClass:
13833 case Expr::ImaginaryLiteralClass:
13834 case Expr::StringLiteralClass:
13835 case Expr::ArraySubscriptExprClass:
13836 case Expr::OMPArraySectionExprClass:
13837 case Expr::MemberExprClass:
13838 case Expr::CompoundAssignOperatorClass:
13839 case Expr::CompoundLiteralExprClass:
13840 case Expr::ExtVectorElementExprClass:
13841 case Expr::DesignatedInitExprClass:
13842 case Expr::ArrayInitLoopExprClass:
13843 case Expr::ArrayInitIndexExprClass:
13844 case Expr::NoInitExprClass:
13845 case Expr::DesignatedInitUpdateExprClass:
13846 case Expr::ImplicitValueInitExprClass:
13847 case Expr::ParenListExprClass:
13848 case Expr::VAArgExprClass:
13849 case Expr::AddrLabelExprClass:
13850 case Expr::StmtExprClass:
13851 case Expr::CXXMemberCallExprClass:
13852 case Expr::CUDAKernelCallExprClass:
13853 case Expr::CXXDynamicCastExprClass:
13854 case Expr::CXXTypeidExprClass:
13855 case Expr::CXXUuidofExprClass:
13856 case Expr::MSPropertyRefExprClass:
13857 case Expr::MSPropertySubscriptExprClass:
13858 case Expr::CXXNullPtrLiteralExprClass:
13859 case Expr::UserDefinedLiteralClass:
13860 case Expr::CXXThisExprClass:
13861 case Expr::CXXThrowExprClass:
13862 case Expr::CXXNewExprClass:
13863 case Expr::CXXDeleteExprClass:
13864 case Expr::CXXPseudoDestructorExprClass:
13865 case Expr::UnresolvedLookupExprClass:
13866 case Expr::TypoExprClass:
13867 case Expr::DependentScopeDeclRefExprClass:
13868 case Expr::CXXConstructExprClass:
13869 case Expr::CXXInheritedCtorInitExprClass:
13870 case Expr::CXXStdInitializerListExprClass:
13871 case Expr::CXXBindTemporaryExprClass:
13872 case Expr::ExprWithCleanupsClass:
13873 case Expr::CXXTemporaryObjectExprClass:
13874 case Expr::CXXUnresolvedConstructExprClass:
13875 case Expr::CXXDependentScopeMemberExprClass:
13876 case Expr::UnresolvedMemberExprClass:
13877 case Expr::ObjCStringLiteralClass:
13878 case Expr::ObjCBoxedExprClass:
13879 case Expr::ObjCArrayLiteralClass:
13880 case Expr::ObjCDictionaryLiteralClass:
13881 case Expr::ObjCEncodeExprClass:
13882 case Expr::ObjCMessageExprClass:
13883 case Expr::ObjCSelectorExprClass:
13884 case Expr::ObjCProtocolExprClass:
13885 case Expr::ObjCIvarRefExprClass:
13886 case Expr::ObjCPropertyRefExprClass:
13887 case Expr::ObjCSubscriptRefExprClass:
13888 case Expr::ObjCIsaExprClass:
13889 case Expr::ObjCAvailabilityCheckExprClass:
13890 case Expr::ShuffleVectorExprClass:
13891 case Expr::ConvertVectorExprClass:
13892 case Expr::BlockExprClass:
13893 case Expr::NoStmtClass:
13894 case Expr::OpaqueValueExprClass:
13895 case Expr::PackExpansionExprClass:
13896 case Expr::SubstNonTypeTemplateParmPackExprClass:
13897 case Expr::FunctionParmPackExprClass:
13898 case Expr::AsTypeExprClass:
13899 case Expr::ObjCIndirectCopyRestoreExprClass:
13900 case Expr::MaterializeTemporaryExprClass:
13901 case Expr::PseudoObjectExprClass:
13902 case Expr::AtomicExprClass:
13903 case Expr::LambdaExprClass:
13904 case Expr::CXXFoldExprClass:
13905 case Expr::CoawaitExprClass:
13906 case Expr::DependentCoawaitExprClass:
13907 case Expr::CoyieldExprClass:
13908 return ICEDiag(IK_NotICE, E->getBeginLoc());
13910 case Expr::InitListExprClass: {
13911 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13912 // form "T x = { a };" is equivalent to "T x = a;".
13913 // Unless we're initializing a reference, T is a scalar as it is known to be
13914 // of integral or enumeration type.
13916 if (cast<InitListExpr>(E)->getNumInits() == 1)
13917 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
13918 return ICEDiag(IK_NotICE, E->getBeginLoc());
13921 case Expr::SizeOfPackExprClass:
13922 case Expr::GNUNullExprClass:
13923 case Expr::SourceLocExprClass:
13926 case Expr::SubstNonTypeTemplateParmExprClass:
13928 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13930 case Expr::ConstantExprClass:
13931 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13933 case Expr::ParenExprClass:
13934 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
13935 case Expr::GenericSelectionExprClass:
13936 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
13937 case Expr::IntegerLiteralClass:
13938 case Expr::FixedPointLiteralClass:
13939 case Expr::CharacterLiteralClass:
13940 case Expr::ObjCBoolLiteralExprClass:
13941 case Expr::CXXBoolLiteralExprClass:
13942 case Expr::CXXScalarValueInitExprClass:
13943 case Expr::TypeTraitExprClass:
13944 case Expr::ConceptSpecializationExprClass:
13945 case Expr::ArrayTypeTraitExprClass:
13946 case Expr::ExpressionTraitExprClass:
13947 case Expr::CXXNoexceptExprClass:
13949 case Expr::CallExprClass:
13950 case Expr::CXXOperatorCallExprClass: {
13951 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13952 // constant expressions, but they can never be ICEs because an ICE cannot
13953 // contain an operand of (pointer to) function type.
13954 const CallExpr *CE = cast<CallExpr>(E);
13955 if (CE->getBuiltinCallee())
13956 return CheckEvalInICE(E, Ctx);
13957 return ICEDiag(IK_NotICE, E->getBeginLoc());
13959 case Expr::CXXRewrittenBinaryOperatorClass:
13960 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
13962 case Expr::DeclRefExprClass: {
13963 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13965 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
13966 if (Ctx.getLangOpts().CPlusPlus &&
13967 D && IsConstNonVolatile(D->getType())) {
13968 // Parameter variables are never constants. Without this check,
13969 // getAnyInitializer() can find a default argument, which leads
13971 if (isa<ParmVarDecl>(D))
13972 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13975 // A variable of non-volatile const-qualified integral or enumeration
13976 // type initialized by an ICE can be used in ICEs.
13977 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
13978 if (!Dcl->getType()->isIntegralOrEnumerationType())
13979 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13982 // Look for a declaration of this variable that has an initializer, and
13983 // check whether it is an ICE.
13984 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13987 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13990 return ICEDiag(IK_NotICE, E->getBeginLoc());
13992 case Expr::UnaryOperatorClass: {
13993 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13994 switch (Exp->getOpcode()) {
14002 // C99 6.6/3 allows increment and decrement within unevaluated
14003 // subexpressions of constant expressions, but they can never be ICEs
14004 // because an ICE cannot contain an lvalue operand.
14005 return ICEDiag(IK_NotICE, E->getBeginLoc());
14013 return CheckICE(Exp->getSubExpr(), Ctx);
14015 llvm_unreachable("invalid unary operator class");
14017 case Expr::OffsetOfExprClass: {
14018 // Note that per C99, offsetof must be an ICE. And AFAIK, using
14019 // EvaluateAsRValue matches the proposed gcc behavior for cases like
14020 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
14021 // compliance: we should warn earlier for offsetof expressions with
14022 // array subscripts that aren't ICEs, and if the array subscripts
14023 // are ICEs, the value of the offsetof must be an integer constant.
14024 return CheckEvalInICE(E, Ctx);
14026 case Expr::UnaryExprOrTypeTraitExprClass: {
14027 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14028 if ((Exp->getKind() == UETT_SizeOf) &&
14029 Exp->getTypeOfArgument()->isVariableArrayType())
14030 return ICEDiag(IK_NotICE, E->getBeginLoc());
14033 case Expr::BinaryOperatorClass: {
14034 const BinaryOperator *Exp = cast<BinaryOperator>(E);
14035 switch (Exp->getOpcode()) {
14049 // C99 6.6/3 allows assignments within unevaluated subexpressions of
14050 // constant expressions, but they can never be ICEs because an ICE cannot
14051 // contain an lvalue operand.
14052 return ICEDiag(IK_NotICE, E->getBeginLoc());
14072 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14073 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14074 if (Exp->getOpcode() == BO_Div ||
14075 Exp->getOpcode() == BO_Rem) {
14076 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14077 // we don't evaluate one.
14078 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14079 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14081 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14082 if (REval.isSigned() && REval.isAllOnesValue()) {
14083 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14084 if (LEval.isMinSignedValue())
14085 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14089 if (Exp->getOpcode() == BO_Comma) {
14090 if (Ctx.getLangOpts().C99) {
14091 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14092 // if it isn't evaluated.
14093 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14094 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14096 // In both C89 and C++, commas in ICEs are illegal.
14097 return ICEDiag(IK_NotICE, E->getBeginLoc());
14100 return Worst(LHSResult, RHSResult);
14104 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14105 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14106 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14107 // Rare case where the RHS has a comma "side-effect"; we need
14108 // to actually check the condition to see whether the side
14109 // with the comma is evaluated.
14110 if ((Exp->getOpcode() == BO_LAnd) !=
14111 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14116 return Worst(LHSResult, RHSResult);
14119 llvm_unreachable("invalid binary operator kind");
14121 case Expr::ImplicitCastExprClass:
14122 case Expr::CStyleCastExprClass:
14123 case Expr::CXXFunctionalCastExprClass:
14124 case Expr::CXXStaticCastExprClass:
14125 case Expr::CXXReinterpretCastExprClass:
14126 case Expr::CXXConstCastExprClass:
14127 case Expr::ObjCBridgedCastExprClass: {
14128 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14129 if (isa<ExplicitCastExpr>(E)) {
14130 if (const FloatingLiteral *FL
14131 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14132 unsigned DestWidth = Ctx.getIntWidth(E->getType());
14133 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14134 APSInt IgnoredVal(DestWidth, !DestSigned);
14136 // If the value does not fit in the destination type, the behavior is
14137 // undefined, so we are not required to treat it as a constant
14139 if (FL->getValue().convertToInteger(IgnoredVal,
14140 llvm::APFloat::rmTowardZero,
14141 &Ignored) & APFloat::opInvalidOp)
14142 return ICEDiag(IK_NotICE, E->getBeginLoc());
14146 switch (cast<CastExpr>(E)->getCastKind()) {
14147 case CK_LValueToRValue:
14148 case CK_AtomicToNonAtomic:
14149 case CK_NonAtomicToAtomic:
14151 case CK_IntegralToBoolean:
14152 case CK_IntegralCast:
14153 return CheckICE(SubExpr, Ctx);
14155 return ICEDiag(IK_NotICE, E->getBeginLoc());
14158 case Expr::BinaryConditionalOperatorClass: {
14159 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14160 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14161 if (CommonResult.Kind == IK_NotICE) return CommonResult;
14162 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14163 if (FalseResult.Kind == IK_NotICE) return FalseResult;
14164 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14165 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14166 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14167 return FalseResult;
14169 case Expr::ConditionalOperatorClass: {
14170 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14171 // If the condition (ignoring parens) is a __builtin_constant_p call,
14172 // then only the true side is actually considered in an integer constant
14173 // expression, and it is fully evaluated. This is an important GNU
14174 // extension. See GCC PR38377 for discussion.
14175 if (const CallExpr *CallCE
14176 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14177 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14178 return CheckEvalInICE(E, Ctx);
14179 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14180 if (CondResult.Kind == IK_NotICE)
14183 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14184 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14186 if (TrueResult.Kind == IK_NotICE)
14188 if (FalseResult.Kind == IK_NotICE)
14189 return FalseResult;
14190 if (CondResult.Kind == IK_ICEIfUnevaluated)
14192 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14194 // Rare case where the diagnostics depend on which side is evaluated
14195 // Note that if we get here, CondResult is 0, and at least one of
14196 // TrueResult and FalseResult is non-zero.
14197 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14198 return FalseResult;
14201 case Expr::CXXDefaultArgExprClass:
14202 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14203 case Expr::CXXDefaultInitExprClass:
14204 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14205 case Expr::ChooseExprClass: {
14206 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14208 case Expr::BuiltinBitCastExprClass: {
14209 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14210 return ICEDiag(IK_NotICE, E->getBeginLoc());
14211 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14215 llvm_unreachable("Invalid StmtClass!");
14218 /// Evaluate an expression as a C++11 integral constant expression.
14219 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14221 llvm::APSInt *Value,
14222 SourceLocation *Loc) {
14223 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14224 if (Loc) *Loc = E->getExprLoc();
14229 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14232 if (!Result.isInt()) {
14233 if (Loc) *Loc = E->getExprLoc();
14237 if (Value) *Value = Result.getInt();
14241 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14242 SourceLocation *Loc) const {
14243 assert(!isValueDependent() &&
14244 "Expression evaluator can't be called on a dependent expression.");
14246 if (Ctx.getLangOpts().CPlusPlus11)
14247 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14249 ICEDiag D = CheckICE(this, Ctx);
14250 if (D.Kind != IK_ICE) {
14251 if (Loc) *Loc = D.Loc;
14257 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14258 SourceLocation *Loc, bool isEvaluated) const {
14259 assert(!isValueDependent() &&
14260 "Expression evaluator can't be called on a dependent expression.");
14262 if (Ctx.getLangOpts().CPlusPlus11)
14263 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14265 if (!isIntegerConstantExpr(Ctx, Loc))
14268 // The only possible side-effects here are due to UB discovered in the
14269 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14270 // required to treat the expression as an ICE, so we produce the folded
14272 EvalResult ExprResult;
14273 Expr::EvalStatus Status;
14274 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14275 Info.InConstantContext = true;
14277 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14278 llvm_unreachable("ICE cannot be evaluated!");
14280 Value = ExprResult.Val.getInt();
14284 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14285 assert(!isValueDependent() &&
14286 "Expression evaluator can't be called on a dependent expression.");
14288 return CheckICE(this, Ctx).Kind == IK_ICE;
14291 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14292 SourceLocation *Loc) const {
14293 assert(!isValueDependent() &&
14294 "Expression evaluator can't be called on a dependent expression.");
14296 // We support this checking in C++98 mode in order to diagnose compatibility
14298 assert(Ctx.getLangOpts().CPlusPlus);
14300 // Build evaluation settings.
14301 Expr::EvalStatus Status;
14302 SmallVector<PartialDiagnosticAt, 8> Diags;
14303 Status.Diag = &Diags;
14304 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14308 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14309 // FIXME: We don't produce a diagnostic for this, but the callers that
14310 // call us on arbitrary full-expressions should generally not care.
14311 Info.discardCleanups() && !Status.HasSideEffects;
14313 if (!Diags.empty()) {
14314 IsConstExpr = false;
14315 if (Loc) *Loc = Diags[0].first;
14316 } else if (!IsConstExpr) {
14317 // FIXME: This shouldn't happen.
14318 if (Loc) *Loc = getExprLoc();
14321 return IsConstExpr;
14324 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14325 const FunctionDecl *Callee,
14326 ArrayRef<const Expr*> Args,
14327 const Expr *This) const {
14328 assert(!isValueDependent() &&
14329 "Expression evaluator can't be called on a dependent expression.");
14331 Expr::EvalStatus Status;
14332 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14333 Info.InConstantContext = true;
14336 const LValue *ThisPtr = nullptr;
14339 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14340 assert(MD && "Don't provide `this` for non-methods.");
14341 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14343 if (EvaluateObjectArgument(Info, This, ThisVal))
14344 ThisPtr = &ThisVal;
14345 if (Info.EvalStatus.HasSideEffects)
14349 ArgVector ArgValues(Args.size());
14350 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14352 if ((*I)->isValueDependent() ||
14353 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
14354 // If evaluation fails, throw away the argument entirely.
14355 ArgValues[I - Args.begin()] = APValue();
14356 if (Info.EvalStatus.HasSideEffects)
14360 // Build fake call to Callee.
14361 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14363 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
14364 !Info.EvalStatus.HasSideEffects;
14367 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14369 PartialDiagnosticAt> &Diags) {
14370 // FIXME: It would be useful to check constexpr function templates, but at the
14371 // moment the constant expression evaluator cannot cope with the non-rigorous
14372 // ASTs which we build for dependent expressions.
14373 if (FD->isDependentContext())
14376 Expr::EvalStatus Status;
14377 Status.Diag = &Diags;
14379 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14380 Info.InConstantContext = true;
14381 Info.CheckingPotentialConstantExpression = true;
14383 // The constexpr VM attempts to compile all methods to bytecode here.
14384 if (Info.EnableNewConstInterp) {
14385 auto &InterpCtx = Info.Ctx.getInterpContext();
14386 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
14387 case interp::InterpResult::Success:
14388 case interp::InterpResult::Fail:
14389 return Diags.empty();
14390 case interp::InterpResult::Bail:
14395 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14396 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14398 // Fabricate an arbitrary expression on the stack and pretend that it
14399 // is a temporary being used as the 'this' pointer.
14401 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14402 This.set({&VIE, Info.CurrentCall->Index});
14404 ArrayRef<const Expr*> Args;
14407 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14408 // Evaluate the call as a constant initializer, to allow the construction
14409 // of objects of non-literal types.
14410 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14411 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14413 SourceLocation Loc = FD->getLocation();
14414 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14415 Args, FD->getBody(), Info, Scratch, nullptr);
14418 return Diags.empty();
14421 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14422 const FunctionDecl *FD,
14424 PartialDiagnosticAt> &Diags) {
14425 assert(!E->isValueDependent() &&
14426 "Expression evaluator can't be called on a dependent expression.");
14428 Expr::EvalStatus Status;
14429 Status.Diag = &Diags;
14431 EvalInfo Info(FD->getASTContext(), Status,
14432 EvalInfo::EM_ConstantExpressionUnevaluated);
14433 Info.InConstantContext = true;
14434 Info.CheckingPotentialConstantExpression = true;
14436 // Fabricate a call stack frame to give the arguments a plausible cover story.
14437 ArrayRef<const Expr*> Args;
14438 ArgVector ArgValues(0);
14439 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14442 "Failed to set up arguments for potential constant evaluation");
14443 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14445 APValue ResultScratch;
14446 Evaluate(ResultScratch, Info, E);
14447 return Diags.empty();
14450 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14451 unsigned Type) const {
14452 if (!getType()->isPointerType())
14455 Expr::EvalStatus Status;
14456 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14457 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);