Path: blob/main/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp
35260 views
//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Expr constant evaluator.9//10// Constant expression evaluation produces four main results:11//12// * A success/failure flag indicating whether constant folding was successful.13// This is the 'bool' return value used by most of the code in this file. A14// 'false' return value indicates that constant folding has failed, and any15// appropriate diagnostic has already been produced.16//17// * An evaluated result, valid only if constant folding has not failed.18//19// * A flag indicating if evaluation encountered (unevaluated) side-effects.20// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),21// where it is possible to determine the evaluated result regardless.22//23// * A set of notes indicating why the evaluation was not a constant expression24// (under the C++11 / C++1y rules only, at the moment), or, if folding failed25// too, why the expression could not be folded.26//27// If we are checking for a potential constant expression, failure to constant28// fold a potential constant sub-expression will be indicated by a 'false'29// return value (the expression could not be folded) and no diagnostic (the30// expression is not necessarily non-constant).31//32//===----------------------------------------------------------------------===//3334#include "ExprConstShared.h"35#include "Interp/Context.h"36#include "Interp/Frame.h"37#include "Interp/State.h"38#include "clang/AST/APValue.h"39#include "clang/AST/ASTContext.h"40#include "clang/AST/ASTDiagnostic.h"41#include "clang/AST/ASTLambda.h"42#include "clang/AST/Attr.h"43#include "clang/AST/CXXInheritance.h"44#include "clang/AST/CharUnits.h"45#include "clang/AST/CurrentSourceLocExprScope.h"46#include "clang/AST/Expr.h"47#include "clang/AST/OSLog.h"48#include "clang/AST/OptionalDiagnostic.h"49#include "clang/AST/RecordLayout.h"50#include "clang/AST/StmtVisitor.h"51#include "clang/AST/TypeLoc.h"52#include "clang/Basic/Builtins.h"53#include "clang/Basic/DiagnosticSema.h"54#include "clang/Basic/TargetInfo.h"55#include "llvm/ADT/APFixedPoint.h"56#include "llvm/ADT/SmallBitVector.h"57#include "llvm/ADT/StringExtras.h"58#include "llvm/Support/Debug.h"59#include "llvm/Support/SaveAndRestore.h"60#include "llvm/Support/SipHash.h"61#include "llvm/Support/TimeProfiler.h"62#include "llvm/Support/raw_ostream.h"63#include <cstring>64#include <functional>65#include <optional>6667#define DEBUG_TYPE "exprconstant"6869using namespace clang;70using llvm::APFixedPoint;71using llvm::APInt;72using llvm::APSInt;73using llvm::APFloat;74using llvm::FixedPointSemantics;7576namespace {77struct LValue;78class CallStackFrame;79class EvalInfo;8081using SourceLocExprScopeGuard =82CurrentSourceLocExprScope::SourceLocExprScopeGuard;8384static QualType getType(APValue::LValueBase B) {85return B.getType();86}8788/// Get an LValue path entry, which is known to not be an array index, as a89/// field declaration.90static const FieldDecl *getAsField(APValue::LValuePathEntry E) {91return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());92}93/// Get an LValue path entry, which is known to not be an array index, as a94/// base class declaration.95static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {96return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());97}98/// Determine whether this LValue path entry for a base class names a virtual99/// base class.100static bool isVirtualBaseClass(APValue::LValuePathEntry E) {101return E.getAsBaseOrMember().getInt();102}103104/// Given an expression, determine the type used to store the result of105/// evaluating that expression.106static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {107if (E->isPRValue())108return E->getType();109return Ctx.getLValueReferenceType(E->getType());110}111112/// Given a CallExpr, try to get the alloc_size attribute. May return null.113static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {114if (const FunctionDecl *DirectCallee = CE->getDirectCallee())115return DirectCallee->getAttr<AllocSizeAttr>();116if (const Decl *IndirectCallee = CE->getCalleeDecl())117return IndirectCallee->getAttr<AllocSizeAttr>();118return nullptr;119}120121/// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.122/// This will look through a single cast.123///124/// Returns null if we couldn't unwrap a function with alloc_size.125static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {126if (!E->getType()->isPointerType())127return nullptr;128129E = E->IgnoreParens();130// If we're doing a variable assignment from e.g. malloc(N), there will131// probably be a cast of some kind. In exotic cases, we might also see a132// top-level ExprWithCleanups. Ignore them either way.133if (const auto *FE = dyn_cast<FullExpr>(E))134E = FE->getSubExpr()->IgnoreParens();135136if (const auto *Cast = dyn_cast<CastExpr>(E))137E = Cast->getSubExpr()->IgnoreParens();138139if (const auto *CE = dyn_cast<CallExpr>(E))140return getAllocSizeAttr(CE) ? CE : nullptr;141return nullptr;142}143144/// Determines whether or not the given Base contains a call to a function145/// with the alloc_size attribute.146static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {147const auto *E = Base.dyn_cast<const Expr *>();148return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);149}150151/// Determines whether the given kind of constant expression is only ever152/// used for name mangling. If so, it's permitted to reference things that we153/// can't generate code for (in particular, dllimported functions).154static bool isForManglingOnly(ConstantExprKind Kind) {155switch (Kind) {156case ConstantExprKind::Normal:157case ConstantExprKind::ClassTemplateArgument:158case ConstantExprKind::ImmediateInvocation:159// Note that non-type template arguments of class type are emitted as160// template parameter objects.161return false;162163case ConstantExprKind::NonClassTemplateArgument:164return true;165}166llvm_unreachable("unknown ConstantExprKind");167}168169static bool isTemplateArgument(ConstantExprKind Kind) {170switch (Kind) {171case ConstantExprKind::Normal:172case ConstantExprKind::ImmediateInvocation:173return false;174175case ConstantExprKind::ClassTemplateArgument:176case ConstantExprKind::NonClassTemplateArgument:177return true;178}179llvm_unreachable("unknown ConstantExprKind");180}181182/// The bound to claim that an array of unknown bound has.183/// The value in MostDerivedArraySize is undefined in this case. So, set it184/// to an arbitrary value that's likely to loudly break things if it's used.185static const uint64_t AssumedSizeForUnsizedArray =186std::numeric_limits<uint64_t>::max() / 2;187188/// Determines if an LValue with the given LValueBase will have an unsized189/// array in its designator.190/// Find the path length and type of the most-derived subobject in the given191/// path, and find the size of the containing array, if any.192static unsigned193findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,194ArrayRef<APValue::LValuePathEntry> Path,195uint64_t &ArraySize, QualType &Type, bool &IsArray,196bool &FirstEntryIsUnsizedArray) {197// This only accepts LValueBases from APValues, and APValues don't support198// arrays that lack size info.199assert(!isBaseAnAllocSizeCall(Base) &&200"Unsized arrays shouldn't appear here");201unsigned MostDerivedLength = 0;202Type = getType(Base);203204for (unsigned I = 0, N = Path.size(); I != N; ++I) {205if (Type->isArrayType()) {206const ArrayType *AT = Ctx.getAsArrayType(Type);207Type = AT->getElementType();208MostDerivedLength = I + 1;209IsArray = true;210211if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {212ArraySize = CAT->getZExtSize();213} else {214assert(I == 0 && "unexpected unsized array designator");215FirstEntryIsUnsizedArray = true;216ArraySize = AssumedSizeForUnsizedArray;217}218} else if (Type->isAnyComplexType()) {219const ComplexType *CT = Type->castAs<ComplexType>();220Type = CT->getElementType();221ArraySize = 2;222MostDerivedLength = I + 1;223IsArray = true;224} else if (const FieldDecl *FD = getAsField(Path[I])) {225Type = FD->getType();226ArraySize = 0;227MostDerivedLength = I + 1;228IsArray = false;229} else {230// Path[I] describes a base class.231ArraySize = 0;232IsArray = false;233}234}235return MostDerivedLength;236}237238/// A path from a glvalue to a subobject of that glvalue.239struct SubobjectDesignator {240/// True if the subobject was named in a manner not supported by C++11. Such241/// lvalues can still be folded, but they are not core constant expressions242/// and we cannot perform lvalue-to-rvalue conversions on them.243LLVM_PREFERRED_TYPE(bool)244unsigned Invalid : 1;245246/// Is this a pointer one past the end of an object?247LLVM_PREFERRED_TYPE(bool)248unsigned IsOnePastTheEnd : 1;249250/// Indicator of whether the first entry is an unsized array.251LLVM_PREFERRED_TYPE(bool)252unsigned FirstEntryIsAnUnsizedArray : 1;253254/// Indicator of whether the most-derived object is an array element.255LLVM_PREFERRED_TYPE(bool)256unsigned MostDerivedIsArrayElement : 1;257258/// The length of the path to the most-derived object of which this is a259/// subobject.260unsigned MostDerivedPathLength : 28;261262/// The size of the array of which the most-derived object is an element.263/// This will always be 0 if the most-derived object is not an array264/// element. 0 is not an indicator of whether or not the most-derived object265/// is an array, however, because 0-length arrays are allowed.266///267/// If the current array is an unsized array, the value of this is268/// undefined.269uint64_t MostDerivedArraySize;270271/// The type of the most derived object referred to by this address.272QualType MostDerivedType;273274typedef APValue::LValuePathEntry PathEntry;275276/// The entries on the path from the glvalue to the designated subobject.277SmallVector<PathEntry, 8> Entries;278279SubobjectDesignator() : Invalid(true) {}280281explicit SubobjectDesignator(QualType T)282: Invalid(false), IsOnePastTheEnd(false),283FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),284MostDerivedPathLength(0), MostDerivedArraySize(0),285MostDerivedType(T) {}286287SubobjectDesignator(ASTContext &Ctx, const APValue &V)288: Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),289FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),290MostDerivedPathLength(0), MostDerivedArraySize(0) {291assert(V.isLValue() && "Non-LValue used to make an LValue designator?");292if (!Invalid) {293IsOnePastTheEnd = V.isLValueOnePastTheEnd();294ArrayRef<PathEntry> VEntries = V.getLValuePath();295Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());296if (V.getLValueBase()) {297bool IsArray = false;298bool FirstIsUnsizedArray = false;299MostDerivedPathLength = findMostDerivedSubobject(300Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,301MostDerivedType, IsArray, FirstIsUnsizedArray);302MostDerivedIsArrayElement = IsArray;303FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;304}305}306}307308void truncate(ASTContext &Ctx, APValue::LValueBase Base,309unsigned NewLength) {310if (Invalid)311return;312313assert(Base && "cannot truncate path for null pointer");314assert(NewLength <= Entries.size() && "not a truncation");315316if (NewLength == Entries.size())317return;318Entries.resize(NewLength);319320bool IsArray = false;321bool FirstIsUnsizedArray = false;322MostDerivedPathLength = findMostDerivedSubobject(323Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,324FirstIsUnsizedArray);325MostDerivedIsArrayElement = IsArray;326FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;327}328329void setInvalid() {330Invalid = true;331Entries.clear();332}333334/// Determine whether the most derived subobject is an array without a335/// known bound.336bool isMostDerivedAnUnsizedArray() const {337assert(!Invalid && "Calling this makes no sense on invalid designators");338return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;339}340341/// Determine what the most derived array's size is. Results in an assertion342/// failure if the most derived array lacks a size.343uint64_t getMostDerivedArraySize() const {344assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");345return MostDerivedArraySize;346}347348/// Determine whether this is a one-past-the-end pointer.349bool isOnePastTheEnd() const {350assert(!Invalid);351if (IsOnePastTheEnd)352return true;353if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&354Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==355MostDerivedArraySize)356return true;357return false;358}359360/// Get the range of valid index adjustments in the form361/// {maximum value that can be subtracted from this pointer,362/// maximum value that can be added to this pointer}363std::pair<uint64_t, uint64_t> validIndexAdjustments() {364if (Invalid || isMostDerivedAnUnsizedArray())365return {0, 0};366367// [expr.add]p4: For the purposes of these operators, a pointer to a368// nonarray object behaves the same as a pointer to the first element of369// an array of length one with the type of the object as its element type.370bool IsArray = MostDerivedPathLength == Entries.size() &&371MostDerivedIsArrayElement;372uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()373: (uint64_t)IsOnePastTheEnd;374uint64_t ArraySize =375IsArray ? getMostDerivedArraySize() : (uint64_t)1;376return {ArrayIndex, ArraySize - ArrayIndex};377}378379/// Check that this refers to a valid subobject.380bool isValidSubobject() const {381if (Invalid)382return false;383return !isOnePastTheEnd();384}385/// Check that this refers to a valid subobject, and if not, produce a386/// relevant diagnostic and set the designator as invalid.387bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);388389/// Get the type of the designated object.390QualType getType(ASTContext &Ctx) const {391assert(!Invalid && "invalid designator has no subobject type");392return MostDerivedPathLength == Entries.size()393? MostDerivedType394: Ctx.getRecordType(getAsBaseClass(Entries.back()));395}396397/// Update this designator to refer to the first element within this array.398void addArrayUnchecked(const ConstantArrayType *CAT) {399Entries.push_back(PathEntry::ArrayIndex(0));400401// This is a most-derived object.402MostDerivedType = CAT->getElementType();403MostDerivedIsArrayElement = true;404MostDerivedArraySize = CAT->getZExtSize();405MostDerivedPathLength = Entries.size();406}407/// Update this designator to refer to the first element within the array of408/// elements of type T. This is an array of unknown size.409void addUnsizedArrayUnchecked(QualType ElemTy) {410Entries.push_back(PathEntry::ArrayIndex(0));411412MostDerivedType = ElemTy;413MostDerivedIsArrayElement = true;414// The value in MostDerivedArraySize is undefined in this case. So, set it415// to an arbitrary value that's likely to loudly break things if it's416// used.417MostDerivedArraySize = AssumedSizeForUnsizedArray;418MostDerivedPathLength = Entries.size();419}420/// Update this designator to refer to the given base or member of this421/// object.422void addDeclUnchecked(const Decl *D, bool Virtual = false) {423Entries.push_back(APValue::BaseOrMemberType(D, Virtual));424425// If this isn't a base class, it's a new most-derived object.426if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {427MostDerivedType = FD->getType();428MostDerivedIsArrayElement = false;429MostDerivedArraySize = 0;430MostDerivedPathLength = Entries.size();431}432}433/// Update this designator to refer to the given complex component.434void addComplexUnchecked(QualType EltTy, bool Imag) {435Entries.push_back(PathEntry::ArrayIndex(Imag));436437// This is technically a most-derived object, though in practice this438// is unlikely to matter.439MostDerivedType = EltTy;440MostDerivedIsArrayElement = true;441MostDerivedArraySize = 2;442MostDerivedPathLength = Entries.size();443}444void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);445void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,446const APSInt &N);447/// Add N to the address of this subobject.448void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {449if (Invalid || !N) return;450uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();451if (isMostDerivedAnUnsizedArray()) {452diagnoseUnsizedArrayPointerArithmetic(Info, E);453// Can't verify -- trust that the user is doing the right thing (or if454// not, trust that the caller will catch the bad behavior).455// FIXME: Should we reject if this overflows, at least?456Entries.back() = PathEntry::ArrayIndex(457Entries.back().getAsArrayIndex() + TruncatedN);458return;459}460461// [expr.add]p4: For the purposes of these operators, a pointer to a462// nonarray object behaves the same as a pointer to the first element of463// an array of length one with the type of the object as its element type.464bool IsArray = MostDerivedPathLength == Entries.size() &&465MostDerivedIsArrayElement;466uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()467: (uint64_t)IsOnePastTheEnd;468uint64_t ArraySize =469IsArray ? getMostDerivedArraySize() : (uint64_t)1;470471if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {472// Calculate the actual index in a wide enough type, so we can include473// it in the note.474N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));475(llvm::APInt&)N += ArrayIndex;476assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");477diagnosePointerArithmetic(Info, E, N);478setInvalid();479return;480}481482ArrayIndex += TruncatedN;483assert(ArrayIndex <= ArraySize &&484"bounds check succeeded for out-of-bounds index");485486if (IsArray)487Entries.back() = PathEntry::ArrayIndex(ArrayIndex);488else489IsOnePastTheEnd = (ArrayIndex != 0);490}491};492493/// A scope at the end of which an object can need to be destroyed.494enum class ScopeKind {495Block,496FullExpression,497Call498};499500/// A reference to a particular call and its arguments.501struct CallRef {502CallRef() : OrigCallee(), CallIndex(0), Version() {}503CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)504: OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}505506explicit operator bool() const { return OrigCallee; }507508/// Get the parameter that the caller initialized, corresponding to the509/// given parameter in the callee.510const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {511return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())512: PVD;513}514515/// The callee at the point where the arguments were evaluated. This might516/// be different from the actual callee (a different redeclaration, or a517/// virtual override), but this function's parameters are the ones that518/// appear in the parameter map.519const FunctionDecl *OrigCallee;520/// The call index of the frame that holds the argument values.521unsigned CallIndex;522/// The version of the parameters corresponding to this call.523unsigned Version;524};525526/// A stack frame in the constexpr call stack.527class CallStackFrame : public interp::Frame {528public:529EvalInfo &Info;530531/// Parent - The caller of this stack frame.532CallStackFrame *Caller;533534/// Callee - The function which was called.535const FunctionDecl *Callee;536537/// This - The binding for the this pointer in this call, if any.538const LValue *This;539540/// CallExpr - The syntactical structure of member function calls541const Expr *CallExpr;542543/// Information on how to find the arguments to this call. Our arguments544/// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a545/// key and this value as the version.546CallRef Arguments;547548/// Source location information about the default argument or default549/// initializer expression we're evaluating, if any.550CurrentSourceLocExprScope CurSourceLocExprScope;551552// Note that we intentionally use std::map here so that references to553// values are stable.554typedef std::pair<const void *, unsigned> MapKeyTy;555typedef std::map<MapKeyTy, APValue> MapTy;556/// Temporaries - Temporary lvalues materialized within this stack frame.557MapTy Temporaries;558559/// CallRange - The source range of the call expression for this call.560SourceRange CallRange;561562/// Index - The call index of this call.563unsigned Index;564565/// The stack of integers for tracking version numbers for temporaries.566SmallVector<unsigned, 2> TempVersionStack = {1};567unsigned CurTempVersion = TempVersionStack.back();568569unsigned getTempVersion() const { return TempVersionStack.back(); }570571void pushTempVersion() {572TempVersionStack.push_back(++CurTempVersion);573}574575void popTempVersion() {576TempVersionStack.pop_back();577}578579CallRef createCall(const FunctionDecl *Callee) {580return {Callee, Index, ++CurTempVersion};581}582583// FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact584// on the overall stack usage of deeply-recursing constexpr evaluations.585// (We should cache this map rather than recomputing it repeatedly.)586// But let's try this and see how it goes; we can look into caching the map587// as a later change.588589/// LambdaCaptureFields - Mapping from captured variables/this to590/// corresponding data members in the closure class.591llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;592FieldDecl *LambdaThisCaptureField = nullptr;593594CallStackFrame(EvalInfo &Info, SourceRange CallRange,595const FunctionDecl *Callee, const LValue *This,596const Expr *CallExpr, CallRef Arguments);597~CallStackFrame();598599// Return the temporary for Key whose version number is Version.600APValue *getTemporary(const void *Key, unsigned Version) {601MapKeyTy KV(Key, Version);602auto LB = Temporaries.lower_bound(KV);603if (LB != Temporaries.end() && LB->first == KV)604return &LB->second;605return nullptr;606}607608// Return the current temporary for Key in the map.609APValue *getCurrentTemporary(const void *Key) {610auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));611if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)612return &std::prev(UB)->second;613return nullptr;614}615616// Return the version number of the current temporary for Key.617unsigned getCurrentTemporaryVersion(const void *Key) const {618auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));619if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)620return std::prev(UB)->first.second;621return 0;622}623624/// Allocate storage for an object of type T in this stack frame.625/// Populates LV with a handle to the created object. Key identifies626/// the temporary within the stack frame, and must not be reused without627/// bumping the temporary version number.628template<typename KeyT>629APValue &createTemporary(const KeyT *Key, QualType T,630ScopeKind Scope, LValue &LV);631632/// Allocate storage for a parameter of a function call made in this frame.633APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);634635void describe(llvm::raw_ostream &OS) const override;636637Frame *getCaller() const override { return Caller; }638SourceRange getCallRange() const override { return CallRange; }639const FunctionDecl *getCallee() const override { return Callee; }640641bool isStdFunction() const {642for (const DeclContext *DC = Callee; DC; DC = DC->getParent())643if (DC->isStdNamespace())644return true;645return false;646}647648/// Whether we're in a context where [[msvc::constexpr]] evaluation is649/// permitted. See MSConstexprDocs for description of permitted contexts.650bool CanEvalMSConstexpr = false;651652private:653APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,654ScopeKind Scope);655};656657/// Temporarily override 'this'.658class ThisOverrideRAII {659public:660ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)661: Frame(Frame), OldThis(Frame.This) {662if (Enable)663Frame.This = NewThis;664}665~ThisOverrideRAII() {666Frame.This = OldThis;667}668private:669CallStackFrame &Frame;670const LValue *OldThis;671};672673// A shorthand time trace scope struct, prints source range, for example674// {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}675class ExprTimeTraceScope {676public:677ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)678: TimeScope(Name, [E, &Ctx] {679return E->getSourceRange().printToString(Ctx.getSourceManager());680}) {}681682private:683llvm::TimeTraceScope TimeScope;684};685686/// RAII object used to change the current ability of687/// [[msvc::constexpr]] evaulation.688struct MSConstexprContextRAII {689CallStackFrame &Frame;690bool OldValue;691explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)692: Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {693Frame.CanEvalMSConstexpr = Value;694}695696~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }697};698}699700static bool HandleDestruction(EvalInfo &Info, const Expr *E,701const LValue &This, QualType ThisType);702static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,703APValue::LValueBase LVBase, APValue &Value,704QualType T);705706namespace {707/// A cleanup, and a flag indicating whether it is lifetime-extended.708class Cleanup {709llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;710APValue::LValueBase Base;711QualType T;712713public:714Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,715ScopeKind Scope)716: Value(Val, Scope), Base(Base), T(T) {}717718/// Determine whether this cleanup should be performed at the end of the719/// given kind of scope.720bool isDestroyedAtEndOf(ScopeKind K) const {721return (int)Value.getInt() >= (int)K;722}723bool endLifetime(EvalInfo &Info, bool RunDestructors) {724if (RunDestructors) {725SourceLocation Loc;726if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())727Loc = VD->getLocation();728else if (const Expr *E = Base.dyn_cast<const Expr*>())729Loc = E->getExprLoc();730return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);731}732*Value.getPointer() = APValue();733return true;734}735736bool hasSideEffect() {737return T.isDestructedType();738}739};740741/// A reference to an object whose construction we are currently evaluating.742struct ObjectUnderConstruction {743APValue::LValueBase Base;744ArrayRef<APValue::LValuePathEntry> Path;745friend bool operator==(const ObjectUnderConstruction &LHS,746const ObjectUnderConstruction &RHS) {747return LHS.Base == RHS.Base && LHS.Path == RHS.Path;748}749friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {750return llvm::hash_combine(Obj.Base, Obj.Path);751}752};753enum class ConstructionPhase {754None,755Bases,756AfterBases,757AfterFields,758Destroying,759DestroyingBases760};761}762763namespace llvm {764template<> struct DenseMapInfo<ObjectUnderConstruction> {765using Base = DenseMapInfo<APValue::LValueBase>;766static ObjectUnderConstruction getEmptyKey() {767return {Base::getEmptyKey(), {}}; }768static ObjectUnderConstruction getTombstoneKey() {769return {Base::getTombstoneKey(), {}};770}771static unsigned getHashValue(const ObjectUnderConstruction &Object) {772return hash_value(Object);773}774static bool isEqual(const ObjectUnderConstruction &LHS,775const ObjectUnderConstruction &RHS) {776return LHS == RHS;777}778};779}780781namespace {782/// A dynamically-allocated heap object.783struct DynAlloc {784/// The value of this heap-allocated object.785APValue Value;786/// The allocating expression; used for diagnostics. Either a CXXNewExpr787/// or a CallExpr (the latter is for direct calls to operator new inside788/// std::allocator<T>::allocate).789const Expr *AllocExpr = nullptr;790791enum Kind {792New,793ArrayNew,794StdAllocator795};796797/// Get the kind of the allocation. This must match between allocation798/// and deallocation.799Kind getKind() const {800if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))801return NE->isArray() ? ArrayNew : New;802assert(isa<CallExpr>(AllocExpr));803return StdAllocator;804}805};806807struct DynAllocOrder {808bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {809return L.getIndex() < R.getIndex();810}811};812813/// EvalInfo - This is a private struct used by the evaluator to capture814/// information about a subexpression as it is folded. It retains information815/// about the AST context, but also maintains information about the folded816/// expression.817///818/// If an expression could be evaluated, it is still possible it is not a C819/// "integer constant expression" or constant expression. If not, this struct820/// captures information about how and why not.821///822/// One bit of information passed *into* the request for constant folding823/// indicates whether the subexpression is "evaluated" or not according to C824/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can825/// evaluate the expression regardless of what the RHS is, but C only allows826/// certain things in certain situations.827class EvalInfo : public interp::State {828public:829ASTContext &Ctx;830831/// EvalStatus - Contains information about the evaluation.832Expr::EvalStatus &EvalStatus;833834/// CurrentCall - The top of the constexpr call stack.835CallStackFrame *CurrentCall;836837/// CallStackDepth - The number of calls in the call stack right now.838unsigned CallStackDepth;839840/// NextCallIndex - The next call index to assign.841unsigned NextCallIndex;842843/// StepsLeft - The remaining number of evaluation steps we're permitted844/// to perform. This is essentially a limit for the number of statements845/// we will evaluate.846unsigned StepsLeft;847848/// Enable the experimental new constant interpreter. If an expression is849/// not supported by the interpreter, an error is triggered.850bool EnableNewConstInterp;851852/// BottomFrame - The frame in which evaluation started. This must be853/// initialized after CurrentCall and CallStackDepth.854CallStackFrame BottomFrame;855856/// A stack of values whose lifetimes end at the end of some surrounding857/// evaluation frame.858llvm::SmallVector<Cleanup, 16> CleanupStack;859860/// EvaluatingDecl - This is the declaration whose initializer is being861/// evaluated, if any.862APValue::LValueBase EvaluatingDecl;863864enum class EvaluatingDeclKind {865None,866/// We're evaluating the construction of EvaluatingDecl.867Ctor,868/// We're evaluating the destruction of EvaluatingDecl.869Dtor,870};871EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;872873/// EvaluatingDeclValue - This is the value being constructed for the874/// declaration whose initializer is being evaluated, if any.875APValue *EvaluatingDeclValue;876877/// Set of objects that are currently being constructed.878llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>879ObjectsUnderConstruction;880881/// Current heap allocations, along with the location where each was882/// allocated. We use std::map here because we need stable addresses883/// for the stored APValues.884std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;885886/// The number of heap allocations performed so far in this evaluation.887unsigned NumHeapAllocs = 0;888889struct EvaluatingConstructorRAII {890EvalInfo &EI;891ObjectUnderConstruction Object;892bool DidInsert;893EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,894bool HasBases)895: EI(EI), Object(Object) {896DidInsert =897EI.ObjectsUnderConstruction898.insert({Object, HasBases ? ConstructionPhase::Bases899: ConstructionPhase::AfterBases})900.second;901}902void finishedConstructingBases() {903EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;904}905void finishedConstructingFields() {906EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;907}908~EvaluatingConstructorRAII() {909if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);910}911};912913struct EvaluatingDestructorRAII {914EvalInfo &EI;915ObjectUnderConstruction Object;916bool DidInsert;917EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)918: EI(EI), Object(Object) {919DidInsert = EI.ObjectsUnderConstruction920.insert({Object, ConstructionPhase::Destroying})921.second;922}923void startedDestroyingBases() {924EI.ObjectsUnderConstruction[Object] =925ConstructionPhase::DestroyingBases;926}927~EvaluatingDestructorRAII() {928if (DidInsert)929EI.ObjectsUnderConstruction.erase(Object);930}931};932933ConstructionPhase934isEvaluatingCtorDtor(APValue::LValueBase Base,935ArrayRef<APValue::LValuePathEntry> Path) {936return ObjectsUnderConstruction.lookup({Base, Path});937}938939/// If we're currently speculatively evaluating, the outermost call stack940/// depth at which we can mutate state, otherwise 0.941unsigned SpeculativeEvaluationDepth = 0;942943/// The current array initialization index, if we're performing array944/// initialization.945uint64_t ArrayInitIndex = -1;946947/// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further948/// notes attached to it will also be stored, otherwise they will not be.949bool HasActiveDiagnostic;950951/// Have we emitted a diagnostic explaining why we couldn't constant952/// fold (not just why it's not strictly a constant expression)?953bool HasFoldFailureDiagnostic;954955/// Whether we're checking that an expression is a potential constant956/// expression. If so, do not fail on constructs that could become constant957/// later on (such as a use of an undefined global).958bool CheckingPotentialConstantExpression = false;959960/// Whether we're checking for an expression that has undefined behavior.961/// If so, we will produce warnings if we encounter an operation that is962/// always undefined.963///964/// Note that we still need to evaluate the expression normally when this965/// is set; this is used when evaluating ICEs in C.966bool CheckingForUndefinedBehavior = false;967968enum EvaluationMode {969/// Evaluate as a constant expression. Stop if we find that the expression970/// is not a constant expression.971EM_ConstantExpression,972973/// Evaluate as a constant expression. Stop if we find that the expression974/// is not a constant expression. Some expressions can be retried in the975/// optimizer if we don't constant fold them here, but in an unevaluated976/// context we try to fold them immediately since the optimizer never977/// gets a chance to look at it.978EM_ConstantExpressionUnevaluated,979980/// Fold the expression to a constant. Stop if we hit a side-effect that981/// we can't model.982EM_ConstantFold,983984/// Evaluate in any way we know how. Don't worry about side-effects that985/// can't be modeled.986EM_IgnoreSideEffects,987} EvalMode;988989/// Are we checking whether the expression is a potential constant990/// expression?991bool checkingPotentialConstantExpression() const override {992return CheckingPotentialConstantExpression;993}994995/// Are we checking an expression for overflow?996// FIXME: We should check for any kind of undefined or suspicious behavior997// in such constructs, not just overflow.998bool checkingForUndefinedBehavior() const override {999return CheckingForUndefinedBehavior;1000}10011002EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)1003: Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),1004CallStackDepth(0), NextCallIndex(1),1005StepsLeft(C.getLangOpts().ConstexprStepLimit),1006EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),1007BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,1008/*This=*/nullptr,1009/*CallExpr=*/nullptr, CallRef()),1010EvaluatingDecl((const ValueDecl *)nullptr),1011EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),1012HasFoldFailureDiagnostic(false), EvalMode(Mode) {}10131014~EvalInfo() {1015discardCleanups();1016}10171018ASTContext &getCtx() const override { return Ctx; }10191020void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,1021EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {1022EvaluatingDecl = Base;1023IsEvaluatingDecl = EDK;1024EvaluatingDeclValue = &Value;1025}10261027bool CheckCallLimit(SourceLocation Loc) {1028// Don't perform any constexpr calls (other than the call we're checking)1029// when checking a potential constant expression.1030if (checkingPotentialConstantExpression() && CallStackDepth > 1)1031return false;1032if (NextCallIndex == 0) {1033// NextCallIndex has wrapped around.1034FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);1035return false;1036}1037if (CallStackDepth <= getLangOpts().ConstexprCallDepth)1038return true;1039FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)1040<< getLangOpts().ConstexprCallDepth;1041return false;1042}10431044bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,1045uint64_t ElemCount, bool Diag) {1046// FIXME: GH635621047// APValue stores array extents as unsigned,1048// so anything that is greater that unsigned would overflow when1049// constructing the array, we catch this here.1050if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||1051ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {1052if (Diag)1053FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;1054return false;1055}10561057// FIXME: GH635621058// Arrays allocate an APValue per element.1059// We use the number of constexpr steps as a proxy for the maximum size1060// of arrays to avoid exhausting the system resources, as initialization1061// of each element is likely to take some number of steps anyway.1062uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;1063if (ElemCount > Limit) {1064if (Diag)1065FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)1066<< ElemCount << Limit;1067return false;1068}1069return true;1070}10711072std::pair<CallStackFrame *, unsigned>1073getCallFrameAndDepth(unsigned CallIndex) {1074assert(CallIndex && "no call index in getCallFrameAndDepth");1075// We will eventually hit BottomFrame, which has Index 1, so Frame can't1076// be null in this loop.1077unsigned Depth = CallStackDepth;1078CallStackFrame *Frame = CurrentCall;1079while (Frame->Index > CallIndex) {1080Frame = Frame->Caller;1081--Depth;1082}1083if (Frame->Index == CallIndex)1084return {Frame, Depth};1085return {nullptr, 0};1086}10871088bool nextStep(const Stmt *S) {1089if (!StepsLeft) {1090FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);1091return false;1092}1093--StepsLeft;1094return true;1095}10961097APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);10981099std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {1100std::optional<DynAlloc *> Result;1101auto It = HeapAllocs.find(DA);1102if (It != HeapAllocs.end())1103Result = &It->second;1104return Result;1105}11061107/// Get the allocated storage for the given parameter of the given call.1108APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {1109CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;1110return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)1111: nullptr;1112}11131114/// Information about a stack frame for std::allocator<T>::[de]allocate.1115struct StdAllocatorCaller {1116unsigned FrameIndex;1117QualType ElemType;1118explicit operator bool() const { return FrameIndex != 0; };1119};11201121StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {1122for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;1123Call = Call->Caller) {1124const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);1125if (!MD)1126continue;1127const IdentifierInfo *FnII = MD->getIdentifier();1128if (!FnII || !FnII->isStr(FnName))1129continue;11301131const auto *CTSD =1132dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());1133if (!CTSD)1134continue;11351136const IdentifierInfo *ClassII = CTSD->getIdentifier();1137const TemplateArgumentList &TAL = CTSD->getTemplateArgs();1138if (CTSD->isInStdNamespace() && ClassII &&1139ClassII->isStr("allocator") && TAL.size() >= 1 &&1140TAL[0].getKind() == TemplateArgument::Type)1141return {Call->Index, TAL[0].getAsType()};1142}11431144return {};1145}11461147void performLifetimeExtension() {1148// Disable the cleanups for lifetime-extended temporaries.1149llvm::erase_if(CleanupStack, [](Cleanup &C) {1150return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);1151});1152}11531154/// Throw away any remaining cleanups at the end of evaluation. If any1155/// cleanups would have had a side-effect, note that as an unmodeled1156/// side-effect and return false. Otherwise, return true.1157bool discardCleanups() {1158for (Cleanup &C : CleanupStack) {1159if (C.hasSideEffect() && !noteSideEffect()) {1160CleanupStack.clear();1161return false;1162}1163}1164CleanupStack.clear();1165return true;1166}11671168private:1169interp::Frame *getCurrentFrame() override { return CurrentCall; }1170const interp::Frame *getBottomFrame() const override { return &BottomFrame; }11711172bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }1173void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }11741175void setFoldFailureDiagnostic(bool Flag) override {1176HasFoldFailureDiagnostic = Flag;1177}11781179Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }11801181// If we have a prior diagnostic, it will be noting that the expression1182// isn't a constant expression. This diagnostic is more important,1183// unless we require this evaluation to produce a constant expression.1184//1185// FIXME: We might want to show both diagnostics to the user in1186// EM_ConstantFold mode.1187bool hasPriorDiagnostic() override {1188if (!EvalStatus.Diag->empty()) {1189switch (EvalMode) {1190case EM_ConstantFold:1191case EM_IgnoreSideEffects:1192if (!HasFoldFailureDiagnostic)1193break;1194// We've already failed to fold something. Keep that diagnostic.1195[[fallthrough]];1196case EM_ConstantExpression:1197case EM_ConstantExpressionUnevaluated:1198setActiveDiagnostic(false);1199return true;1200}1201}1202return false;1203}12041205unsigned getCallStackDepth() override { return CallStackDepth; }12061207public:1208/// Should we continue evaluation after encountering a side-effect that we1209/// couldn't model?1210bool keepEvaluatingAfterSideEffect() {1211switch (EvalMode) {1212case EM_IgnoreSideEffects:1213return true;12141215case EM_ConstantExpression:1216case EM_ConstantExpressionUnevaluated:1217case EM_ConstantFold:1218// By default, assume any side effect might be valid in some other1219// evaluation of this expression from a different context.1220return checkingPotentialConstantExpression() ||1221checkingForUndefinedBehavior();1222}1223llvm_unreachable("Missed EvalMode case");1224}12251226/// Note that we have had a side-effect, and determine whether we should1227/// keep evaluating.1228bool noteSideEffect() {1229EvalStatus.HasSideEffects = true;1230return keepEvaluatingAfterSideEffect();1231}12321233/// Should we continue evaluation after encountering undefined behavior?1234bool keepEvaluatingAfterUndefinedBehavior() {1235switch (EvalMode) {1236case EM_IgnoreSideEffects:1237case EM_ConstantFold:1238return true;12391240case EM_ConstantExpression:1241case EM_ConstantExpressionUnevaluated:1242return checkingForUndefinedBehavior();1243}1244llvm_unreachable("Missed EvalMode case");1245}12461247/// Note that we hit something that was technically undefined behavior, but1248/// that we can evaluate past it (such as signed overflow or floating-point1249/// division by zero.)1250bool noteUndefinedBehavior() override {1251EvalStatus.HasUndefinedBehavior = true;1252return keepEvaluatingAfterUndefinedBehavior();1253}12541255/// Should we continue evaluation as much as possible after encountering a1256/// construct which can't be reduced to a value?1257bool keepEvaluatingAfterFailure() const override {1258if (!StepsLeft)1259return false;12601261switch (EvalMode) {1262case EM_ConstantExpression:1263case EM_ConstantExpressionUnevaluated:1264case EM_ConstantFold:1265case EM_IgnoreSideEffects:1266return checkingPotentialConstantExpression() ||1267checkingForUndefinedBehavior();1268}1269llvm_unreachable("Missed EvalMode case");1270}12711272/// Notes that we failed to evaluate an expression that other expressions1273/// directly depend on, and determine if we should keep evaluating. This1274/// should only be called if we actually intend to keep evaluating.1275///1276/// Call noteSideEffect() instead if we may be able to ignore the value that1277/// we failed to evaluate, e.g. if we failed to evaluate Foo() in:1278///1279/// (Foo(), 1) // use noteSideEffect1280/// (Foo() || true) // use noteSideEffect1281/// Foo() + 1 // use noteFailure1282[[nodiscard]] bool noteFailure() {1283// Failure when evaluating some expression often means there is some1284// subexpression whose evaluation was skipped. Therefore, (because we1285// don't track whether we skipped an expression when unwinding after an1286// evaluation failure) every evaluation failure that bubbles up from a1287// subexpression implies that a side-effect has potentially happened. We1288// skip setting the HasSideEffects flag to true until we decide to1289// continue evaluating after that point, which happens here.1290bool KeepGoing = keepEvaluatingAfterFailure();1291EvalStatus.HasSideEffects |= KeepGoing;1292return KeepGoing;1293}12941295class ArrayInitLoopIndex {1296EvalInfo &Info;1297uint64_t OuterIndex;12981299public:1300ArrayInitLoopIndex(EvalInfo &Info)1301: Info(Info), OuterIndex(Info.ArrayInitIndex) {1302Info.ArrayInitIndex = 0;1303}1304~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }13051306operator uint64_t&() { return Info.ArrayInitIndex; }1307};1308};13091310/// Object used to treat all foldable expressions as constant expressions.1311struct FoldConstant {1312EvalInfo &Info;1313bool Enabled;1314bool HadNoPriorDiags;1315EvalInfo::EvaluationMode OldMode;13161317explicit FoldConstant(EvalInfo &Info, bool Enabled)1318: Info(Info),1319Enabled(Enabled),1320HadNoPriorDiags(Info.EvalStatus.Diag &&1321Info.EvalStatus.Diag->empty() &&1322!Info.EvalStatus.HasSideEffects),1323OldMode(Info.EvalMode) {1324if (Enabled)1325Info.EvalMode = EvalInfo::EM_ConstantFold;1326}1327void keepDiagnostics() { Enabled = false; }1328~FoldConstant() {1329if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&1330!Info.EvalStatus.HasSideEffects)1331Info.EvalStatus.Diag->clear();1332Info.EvalMode = OldMode;1333}1334};13351336/// RAII object used to set the current evaluation mode to ignore1337/// side-effects.1338struct IgnoreSideEffectsRAII {1339EvalInfo &Info;1340EvalInfo::EvaluationMode OldMode;1341explicit IgnoreSideEffectsRAII(EvalInfo &Info)1342: Info(Info), OldMode(Info.EvalMode) {1343Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;1344}13451346~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }1347};13481349/// RAII object used to optionally suppress diagnostics and side-effects from1350/// a speculative evaluation.1351class SpeculativeEvaluationRAII {1352EvalInfo *Info = nullptr;1353Expr::EvalStatus OldStatus;1354unsigned OldSpeculativeEvaluationDepth = 0;13551356void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {1357Info = Other.Info;1358OldStatus = Other.OldStatus;1359OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;1360Other.Info = nullptr;1361}13621363void maybeRestoreState() {1364if (!Info)1365return;13661367Info->EvalStatus = OldStatus;1368Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;1369}13701371public:1372SpeculativeEvaluationRAII() = default;13731374SpeculativeEvaluationRAII(1375EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)1376: Info(&Info), OldStatus(Info.EvalStatus),1377OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {1378Info.EvalStatus.Diag = NewDiag;1379Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;1380}13811382SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;1383SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {1384moveFromAndCancel(std::move(Other));1385}13861387SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {1388maybeRestoreState();1389moveFromAndCancel(std::move(Other));1390return *this;1391}13921393~SpeculativeEvaluationRAII() { maybeRestoreState(); }1394};13951396/// RAII object wrapping a full-expression or block scope, and handling1397/// the ending of the lifetime of temporaries created within it.1398template<ScopeKind Kind>1399class ScopeRAII {1400EvalInfo &Info;1401unsigned OldStackSize;1402public:1403ScopeRAII(EvalInfo &Info)1404: Info(Info), OldStackSize(Info.CleanupStack.size()) {1405// Push a new temporary version. This is needed to distinguish between1406// temporaries created in different iterations of a loop.1407Info.CurrentCall->pushTempVersion();1408}1409bool destroy(bool RunDestructors = true) {1410bool OK = cleanup(Info, RunDestructors, OldStackSize);1411OldStackSize = -1U;1412return OK;1413}1414~ScopeRAII() {1415if (OldStackSize != -1U)1416destroy(false);1417// Body moved to a static method to encourage the compiler to inline away1418// instances of this class.1419Info.CurrentCall->popTempVersion();1420}1421private:1422static bool cleanup(EvalInfo &Info, bool RunDestructors,1423unsigned OldStackSize) {1424assert(OldStackSize <= Info.CleanupStack.size() &&1425"running cleanups out of order?");14261427// Run all cleanups for a block scope, and non-lifetime-extended cleanups1428// for a full-expression scope.1429bool Success = true;1430for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {1431if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {1432if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {1433Success = false;1434break;1435}1436}1437}14381439// Compact any retained cleanups.1440auto NewEnd = Info.CleanupStack.begin() + OldStackSize;1441if (Kind != ScopeKind::Block)1442NewEnd =1443std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {1444return C.isDestroyedAtEndOf(Kind);1445});1446Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());1447return Success;1448}1449};1450typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;1451typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;1452typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;1453}14541455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,1456CheckSubobjectKind CSK) {1457if (Invalid)1458return false;1459if (isOnePastTheEnd()) {1460Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)1461<< CSK;1462setInvalid();1463return false;1464}1465// Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there1466// must actually be at least one array element; even a VLA cannot have a1467// bound of zero. And if our index is nonzero, we already had a CCEDiag.1468return true;1469}14701471void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,1472const Expr *E) {1473Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);1474// Do not set the designator as invalid: we can represent this situation,1475// and correct handling of __builtin_object_size requires us to do so.1476}14771478void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,1479const Expr *E,1480const APSInt &N) {1481// If we're complaining, we must be able to statically determine the size of1482// the most derived array.1483if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)1484Info.CCEDiag(E, diag::note_constexpr_array_index)1485<< N << /*array*/ 01486<< static_cast<unsigned>(getMostDerivedArraySize());1487else1488Info.CCEDiag(E, diag::note_constexpr_array_index)1489<< N << /*non-array*/ 1;1490setInvalid();1491}14921493CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,1494const FunctionDecl *Callee, const LValue *This,1495const Expr *CallExpr, CallRef Call)1496: Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),1497CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),1498Index(Info.NextCallIndex++) {1499Info.CurrentCall = this;1500++Info.CallStackDepth;1501}15021503CallStackFrame::~CallStackFrame() {1504assert(Info.CurrentCall == this && "calls retired out of order");1505--Info.CallStackDepth;1506Info.CurrentCall = Caller;1507}15081509static bool isRead(AccessKinds AK) {1510return AK == AK_Read || AK == AK_ReadObjectRepresentation;1511}15121513static bool isModification(AccessKinds AK) {1514switch (AK) {1515case AK_Read:1516case AK_ReadObjectRepresentation:1517case AK_MemberCall:1518case AK_DynamicCast:1519case AK_TypeId:1520return false;1521case AK_Assign:1522case AK_Increment:1523case AK_Decrement:1524case AK_Construct:1525case AK_Destroy:1526return true;1527}1528llvm_unreachable("unknown access kind");1529}15301531static bool isAnyAccess(AccessKinds AK) {1532return isRead(AK) || isModification(AK);1533}15341535/// Is this an access per the C++ definition?1536static bool isFormalAccess(AccessKinds AK) {1537return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;1538}15391540/// Is this kind of axcess valid on an indeterminate object value?1541static bool isValidIndeterminateAccess(AccessKinds AK) {1542switch (AK) {1543case AK_Read:1544case AK_Increment:1545case AK_Decrement:1546// These need the object's value.1547return false;15481549case AK_ReadObjectRepresentation:1550case AK_Assign:1551case AK_Construct:1552case AK_Destroy:1553// Construction and destruction don't need the value.1554return true;15551556case AK_MemberCall:1557case AK_DynamicCast:1558case AK_TypeId:1559// These aren't really meaningful on scalars.1560return true;1561}1562llvm_unreachable("unknown access kind");1563}15641565namespace {1566struct ComplexValue {1567private:1568bool IsInt;15691570public:1571APSInt IntReal, IntImag;1572APFloat FloatReal, FloatImag;15731574ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}15751576void makeComplexFloat() { IsInt = false; }1577bool isComplexFloat() const { return !IsInt; }1578APFloat &getComplexFloatReal() { return FloatReal; }1579APFloat &getComplexFloatImag() { return FloatImag; }15801581void makeComplexInt() { IsInt = true; }1582bool isComplexInt() const { return IsInt; }1583APSInt &getComplexIntReal() { return IntReal; }1584APSInt &getComplexIntImag() { return IntImag; }15851586void moveInto(APValue &v) const {1587if (isComplexFloat())1588v = APValue(FloatReal, FloatImag);1589else1590v = APValue(IntReal, IntImag);1591}1592void setFrom(const APValue &v) {1593assert(v.isComplexFloat() || v.isComplexInt());1594if (v.isComplexFloat()) {1595makeComplexFloat();1596FloatReal = v.getComplexFloatReal();1597FloatImag = v.getComplexFloatImag();1598} else {1599makeComplexInt();1600IntReal = v.getComplexIntReal();1601IntImag = v.getComplexIntImag();1602}1603}1604};16051606struct LValue {1607APValue::LValueBase Base;1608CharUnits Offset;1609SubobjectDesignator Designator;1610bool IsNullPtr : 1;1611bool InvalidBase : 1;16121613const APValue::LValueBase getLValueBase() const { return Base; }1614CharUnits &getLValueOffset() { return Offset; }1615const CharUnits &getLValueOffset() const { return Offset; }1616SubobjectDesignator &getLValueDesignator() { return Designator; }1617const SubobjectDesignator &getLValueDesignator() const { return Designator;}1618bool isNullPointer() const { return IsNullPtr;}16191620unsigned getLValueCallIndex() const { return Base.getCallIndex(); }1621unsigned getLValueVersion() const { return Base.getVersion(); }16221623void moveInto(APValue &V) const {1624if (Designator.Invalid)1625V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);1626else {1627assert(!InvalidBase && "APValues can't handle invalid LValue bases");1628V = APValue(Base, Offset, Designator.Entries,1629Designator.IsOnePastTheEnd, IsNullPtr);1630}1631}1632void setFrom(ASTContext &Ctx, const APValue &V) {1633assert(V.isLValue() && "Setting LValue from a non-LValue?");1634Base = V.getLValueBase();1635Offset = V.getLValueOffset();1636InvalidBase = false;1637Designator = SubobjectDesignator(Ctx, V);1638IsNullPtr = V.isNullPointer();1639}16401641void set(APValue::LValueBase B, bool BInvalid = false) {1642#ifndef NDEBUG1643// We only allow a few types of invalid bases. Enforce that here.1644if (BInvalid) {1645const auto *E = B.get<const Expr *>();1646assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&1647"Unexpected type of invalid base");1648}1649#endif16501651Base = B;1652Offset = CharUnits::fromQuantity(0);1653InvalidBase = BInvalid;1654Designator = SubobjectDesignator(getType(B));1655IsNullPtr = false;1656}16571658void setNull(ASTContext &Ctx, QualType PointerTy) {1659Base = (const ValueDecl *)nullptr;1660Offset =1661CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));1662InvalidBase = false;1663Designator = SubobjectDesignator(PointerTy->getPointeeType());1664IsNullPtr = true;1665}16661667void setInvalid(APValue::LValueBase B, unsigned I = 0) {1668set(B, true);1669}16701671std::string toString(ASTContext &Ctx, QualType T) const {1672APValue Printable;1673moveInto(Printable);1674return Printable.getAsString(Ctx, T);1675}16761677private:1678// Check that this LValue is not based on a null pointer. If it is, produce1679// a diagnostic and mark the designator as invalid.1680template <typename GenDiagType>1681bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {1682if (Designator.Invalid)1683return false;1684if (IsNullPtr) {1685GenDiag();1686Designator.setInvalid();1687return false;1688}1689return true;1690}16911692public:1693bool checkNullPointer(EvalInfo &Info, const Expr *E,1694CheckSubobjectKind CSK) {1695return checkNullPointerDiagnosingWith([&Info, E, CSK] {1696Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;1697});1698}16991700bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,1701AccessKinds AK) {1702return checkNullPointerDiagnosingWith([&Info, E, AK] {1703Info.FFDiag(E, diag::note_constexpr_access_null) << AK;1704});1705}17061707// Check this LValue refers to an object. If not, set the designator to be1708// invalid and emit a diagnostic.1709bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {1710return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&1711Designator.checkSubobject(Info, E, CSK);1712}17131714void addDecl(EvalInfo &Info, const Expr *E,1715const Decl *D, bool Virtual = false) {1716if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))1717Designator.addDeclUnchecked(D, Virtual);1718}1719void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {1720if (!Designator.Entries.empty()) {1721Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);1722Designator.setInvalid();1723return;1724}1725if (checkSubobject(Info, E, CSK_ArrayToPointer)) {1726assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());1727Designator.FirstEntryIsAnUnsizedArray = true;1728Designator.addUnsizedArrayUnchecked(ElemTy);1729}1730}1731void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {1732if (checkSubobject(Info, E, CSK_ArrayToPointer))1733Designator.addArrayUnchecked(CAT);1734}1735void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {1736if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))1737Designator.addComplexUnchecked(EltTy, Imag);1738}1739void clearIsNullPointer() {1740IsNullPtr = false;1741}1742void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,1743const APSInt &Index, CharUnits ElementSize) {1744// An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,1745// but we're not required to diagnose it and it's valid in C++.)1746if (!Index)1747return;17481749// Compute the new offset in the appropriate width, wrapping at 64 bits.1750// FIXME: When compiling for a 32-bit target, we should use 32-bit1751// offsets.1752uint64_t Offset64 = Offset.getQuantity();1753uint64_t ElemSize64 = ElementSize.getQuantity();1754uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();1755Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);17561757if (checkNullPointer(Info, E, CSK_ArrayIndex))1758Designator.adjustIndex(Info, E, Index);1759clearIsNullPointer();1760}1761void adjustOffset(CharUnits N) {1762Offset += N;1763if (N.getQuantity())1764clearIsNullPointer();1765}1766};17671768struct MemberPtr {1769MemberPtr() {}1770explicit MemberPtr(const ValueDecl *Decl)1771: DeclAndIsDerivedMember(Decl, false) {}17721773/// The member or (direct or indirect) field referred to by this member1774/// pointer, or 0 if this is a null member pointer.1775const ValueDecl *getDecl() const {1776return DeclAndIsDerivedMember.getPointer();1777}1778/// Is this actually a member of some type derived from the relevant class?1779bool isDerivedMember() const {1780return DeclAndIsDerivedMember.getInt();1781}1782/// Get the class which the declaration actually lives in.1783const CXXRecordDecl *getContainingRecord() const {1784return cast<CXXRecordDecl>(1785DeclAndIsDerivedMember.getPointer()->getDeclContext());1786}17871788void moveInto(APValue &V) const {1789V = APValue(getDecl(), isDerivedMember(), Path);1790}1791void setFrom(const APValue &V) {1792assert(V.isMemberPointer());1793DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());1794DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());1795Path.clear();1796ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();1797Path.insert(Path.end(), P.begin(), P.end());1798}17991800/// DeclAndIsDerivedMember - The member declaration, and a flag indicating1801/// whether the member is a member of some class derived from the class type1802/// of the member pointer.1803llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;1804/// Path - The path of base/derived classes from the member declaration's1805/// class (exclusive) to the class type of the member pointer (inclusive).1806SmallVector<const CXXRecordDecl*, 4> Path;18071808/// Perform a cast towards the class of the Decl (either up or down the1809/// hierarchy).1810bool castBack(const CXXRecordDecl *Class) {1811assert(!Path.empty());1812const CXXRecordDecl *Expected;1813if (Path.size() >= 2)1814Expected = Path[Path.size() - 2];1815else1816Expected = getContainingRecord();1817if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {1818// C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),1819// if B does not contain the original member and is not a base or1820// derived class of the class containing the original member, the result1821// of the cast is undefined.1822// C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to1823// (D::*). We consider that to be a language defect.1824return false;1825}1826Path.pop_back();1827return true;1828}1829/// Perform a base-to-derived member pointer cast.1830bool castToDerived(const CXXRecordDecl *Derived) {1831if (!getDecl())1832return true;1833if (!isDerivedMember()) {1834Path.push_back(Derived);1835return true;1836}1837if (!castBack(Derived))1838return false;1839if (Path.empty())1840DeclAndIsDerivedMember.setInt(false);1841return true;1842}1843/// Perform a derived-to-base member pointer cast.1844bool castToBase(const CXXRecordDecl *Base) {1845if (!getDecl())1846return true;1847if (Path.empty())1848DeclAndIsDerivedMember.setInt(true);1849if (isDerivedMember()) {1850Path.push_back(Base);1851return true;1852}1853return castBack(Base);1854}1855};18561857/// Compare two member pointers, which are assumed to be of the same type.1858static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {1859if (!LHS.getDecl() || !RHS.getDecl())1860return !LHS.getDecl() && !RHS.getDecl();1861if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())1862return false;1863return LHS.Path == RHS.Path;1864}1865}18661867static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);1868static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,1869const LValue &This, const Expr *E,1870bool AllowNonLiteralTypes = false);1871static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,1872bool InvalidBaseOK = false);1873static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,1874bool InvalidBaseOK = false);1875static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,1876EvalInfo &Info);1877static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);1878static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);1879static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,1880EvalInfo &Info);1881static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);1882static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);1883static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,1884EvalInfo &Info);1885static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);1886static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,1887EvalInfo &Info,1888std::string *StringResult = nullptr);18891890/// Evaluate an integer or fixed point expression into an APResult.1891static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,1892EvalInfo &Info);18931894/// Evaluate only a fixed point expression into an APResult.1895static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,1896EvalInfo &Info);18971898//===----------------------------------------------------------------------===//1899// Misc utilities1900//===----------------------------------------------------------------------===//19011902/// Negate an APSInt in place, converting it to a signed form if necessary, and1903/// preserving its value (by extending by up to one bit as needed).1904static void negateAsSigned(APSInt &Int) {1905if (Int.isUnsigned() || Int.isMinSignedValue()) {1906Int = Int.extend(Int.getBitWidth() + 1);1907Int.setIsSigned(true);1908}1909Int = -Int;1910}19111912template<typename KeyT>1913APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,1914ScopeKind Scope, LValue &LV) {1915unsigned Version = getTempVersion();1916APValue::LValueBase Base(Key, Index, Version);1917LV.set(Base);1918return createLocal(Base, Key, T, Scope);1919}19201921/// Allocate storage for a parameter of a function call made in this frame.1922APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,1923LValue &LV) {1924assert(Args.CallIndex == Index && "creating parameter in wrong frame");1925APValue::LValueBase Base(PVD, Index, Args.Version);1926LV.set(Base);1927// We always destroy parameters at the end of the call, even if we'd allow1928// them to live to the end of the full-expression at runtime, in order to1929// give portable results and match other compilers.1930return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);1931}19321933APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,1934QualType T, ScopeKind Scope) {1935assert(Base.getCallIndex() == Index && "lvalue for wrong frame");1936unsigned Version = Base.getVersion();1937APValue &Result = Temporaries[MapKeyTy(Key, Version)];1938assert(Result.isAbsent() && "local created multiple times");19391940// If we're creating a local immediately in the operand of a speculative1941// evaluation, don't register a cleanup to be run outside the speculative1942// evaluation context, since we won't actually be able to initialize this1943// object.1944if (Index <= Info.SpeculativeEvaluationDepth) {1945if (T.isDestructedType())1946Info.noteSideEffect();1947} else {1948Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));1949}1950return Result;1951}19521953APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {1954if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {1955FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);1956return nullptr;1957}19581959DynamicAllocLValue DA(NumHeapAllocs++);1960LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));1961auto Result = HeapAllocs.emplace(std::piecewise_construct,1962std::forward_as_tuple(DA), std::tuple<>());1963assert(Result.second && "reused a heap alloc index?");1964Result.first->second.AllocExpr = E;1965return &Result.first->second.Value;1966}19671968/// Produce a string describing the given constexpr call.1969void CallStackFrame::describe(raw_ostream &Out) const {1970unsigned ArgIndex = 0;1971bool IsMemberCall =1972isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&1973cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();19741975if (!IsMemberCall)1976Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),1977/*Qualified=*/false);19781979if (This && IsMemberCall) {1980if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {1981const Expr *Object = MCE->getImplicitObjectArgument();1982Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),1983/*Indentation=*/0);1984if (Object->getType()->isPointerType())1985Out << "->";1986else1987Out << ".";1988} else if (const auto *OCE =1989dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {1990OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,1991Info.Ctx.getPrintingPolicy(),1992/*Indentation=*/0);1993Out << ".";1994} else {1995APValue Val;1996This->moveInto(Val);1997Val.printPretty(1998Out, Info.Ctx,1999Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));2000Out << ".";2001}2002Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),2003/*Qualified=*/false);2004IsMemberCall = false;2005}20062007Out << '(';20082009for (FunctionDecl::param_const_iterator I = Callee->param_begin(),2010E = Callee->param_end(); I != E; ++I, ++ArgIndex) {2011if (ArgIndex > (unsigned)IsMemberCall)2012Out << ", ";20132014const ParmVarDecl *Param = *I;2015APValue *V = Info.getParamSlot(Arguments, Param);2016if (V)2017V->printPretty(Out, Info.Ctx, Param->getType());2018else2019Out << "<...>";20202021if (ArgIndex == 0 && IsMemberCall)2022Out << "->" << *Callee << '(';2023}20242025Out << ')';2026}20272028/// Evaluate an expression to see if it had side-effects, and discard its2029/// result.2030/// \return \c true if the caller should keep evaluating.2031static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {2032assert(!E->isValueDependent());2033APValue Scratch;2034if (!Evaluate(Scratch, Info, E))2035// We don't need the value, but we might have skipped a side effect here.2036return Info.noteSideEffect();2037return true;2038}20392040/// Should this call expression be treated as a no-op?2041static bool IsNoOpCall(const CallExpr *E) {2042unsigned Builtin = E->getBuiltinCallee();2043return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||2044Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||2045Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||2046Builtin == Builtin::BI__builtin_function_start);2047}20482049static bool IsGlobalLValue(APValue::LValueBase B) {2050// C++11 [expr.const]p3 An address constant expression is a prvalue core2051// constant expression of pointer type that evaluates to...20522053// ... a null pointer value, or a prvalue core constant expression of type2054// std::nullptr_t.2055if (!B)2056return true;20572058if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {2059// ... the address of an object with static storage duration,2060if (const VarDecl *VD = dyn_cast<VarDecl>(D))2061return VD->hasGlobalStorage();2062if (isa<TemplateParamObjectDecl>(D))2063return true;2064// ... the address of a function,2065// ... the address of a GUID [MS extension],2066// ... the address of an unnamed global constant2067return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);2068}20692070if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())2071return true;20722073const Expr *E = B.get<const Expr*>();2074switch (E->getStmtClass()) {2075default:2076return false;2077case Expr::CompoundLiteralExprClass: {2078const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);2079return CLE->isFileScope() && CLE->isLValue();2080}2081case Expr::MaterializeTemporaryExprClass:2082// A materialized temporary might have been lifetime-extended to static2083// storage duration.2084return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;2085// A string literal has static storage duration.2086case Expr::StringLiteralClass:2087case Expr::PredefinedExprClass:2088case Expr::ObjCStringLiteralClass:2089case Expr::ObjCEncodeExprClass:2090return true;2091case Expr::ObjCBoxedExprClass:2092return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();2093case Expr::CallExprClass:2094return IsNoOpCall(cast<CallExpr>(E));2095// For GCC compatibility, &&label has static storage duration.2096case Expr::AddrLabelExprClass:2097return true;2098// A Block literal expression may be used as the initialization value for2099// Block variables at global or local static scope.2100case Expr::BlockExprClass:2101return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();2102// The APValue generated from a __builtin_source_location will be emitted as a2103// literal.2104case Expr::SourceLocExprClass:2105return true;2106case Expr::ImplicitValueInitExprClass:2107// FIXME:2108// We can never form an lvalue with an implicit value initialization as its2109// base through expression evaluation, so these only appear in one case: the2110// implicit variable declaration we invent when checking whether a constexpr2111// constructor can produce a constant expression. We must assume that such2112// an expression might be a global lvalue.2113return true;2114}2115}21162117static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {2118return LVal.Base.dyn_cast<const ValueDecl*>();2119}21202121static bool IsLiteralLValue(const LValue &Value) {2122if (Value.getLValueCallIndex())2123return false;2124const Expr *E = Value.Base.dyn_cast<const Expr*>();2125return E && !isa<MaterializeTemporaryExpr>(E);2126}21272128static bool IsWeakLValue(const LValue &Value) {2129const ValueDecl *Decl = GetLValueBaseDecl(Value);2130return Decl && Decl->isWeak();2131}21322133static bool isZeroSized(const LValue &Value) {2134const ValueDecl *Decl = GetLValueBaseDecl(Value);2135if (isa_and_nonnull<VarDecl>(Decl)) {2136QualType Ty = Decl->getType();2137if (Ty->isArrayType())2138return Ty->isIncompleteType() ||2139Decl->getASTContext().getTypeSize(Ty) == 0;2140}2141return false;2142}21432144static bool HasSameBase(const LValue &A, const LValue &B) {2145if (!A.getLValueBase())2146return !B.getLValueBase();2147if (!B.getLValueBase())2148return false;21492150if (A.getLValueBase().getOpaqueValue() !=2151B.getLValueBase().getOpaqueValue())2152return false;21532154return A.getLValueCallIndex() == B.getLValueCallIndex() &&2155A.getLValueVersion() == B.getLValueVersion();2156}21572158static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {2159assert(Base && "no location for a null lvalue");2160const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();21612162// For a parameter, find the corresponding call stack frame (if it still2163// exists), and point at the parameter of the function definition we actually2164// invoked.2165if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {2166unsigned Idx = PVD->getFunctionScopeIndex();2167for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {2168if (F->Arguments.CallIndex == Base.getCallIndex() &&2169F->Arguments.Version == Base.getVersion() && F->Callee &&2170Idx < F->Callee->getNumParams()) {2171VD = F->Callee->getParamDecl(Idx);2172break;2173}2174}2175}21762177if (VD)2178Info.Note(VD->getLocation(), diag::note_declared_at);2179else if (const Expr *E = Base.dyn_cast<const Expr*>())2180Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);2181else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {2182// FIXME: Produce a note for dangling pointers too.2183if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))2184Info.Note((*Alloc)->AllocExpr->getExprLoc(),2185diag::note_constexpr_dynamic_alloc_here);2186}21872188// We have no information to show for a typeid(T) object.2189}21902191enum class CheckEvaluationResultKind {2192ConstantExpression,2193FullyInitialized,2194};21952196/// Materialized temporaries that we've already checked to determine if they're2197/// initializsed by a constant expression.2198using CheckedTemporaries =2199llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;22002201static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,2202EvalInfo &Info, SourceLocation DiagLoc,2203QualType Type, const APValue &Value,2204ConstantExprKind Kind,2205const FieldDecl *SubobjectDecl,2206CheckedTemporaries &CheckedTemps);22072208/// Check that this reference or pointer core constant expression is a valid2209/// value for an address or reference constant expression. Return true if we2210/// can fold this expression, whether or not it's a constant expression.2211static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,2212QualType Type, const LValue &LVal,2213ConstantExprKind Kind,2214CheckedTemporaries &CheckedTemps) {2215bool IsReferenceType = Type->isReferenceType();22162217APValue::LValueBase Base = LVal.getLValueBase();2218const SubobjectDesignator &Designator = LVal.getLValueDesignator();22192220const Expr *BaseE = Base.dyn_cast<const Expr *>();2221const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();22222223// Additional restrictions apply in a template argument. We only enforce the2224// C++20 restrictions here; additional syntactic and semantic restrictions2225// are applied elsewhere.2226if (isTemplateArgument(Kind)) {2227int InvalidBaseKind = -1;2228StringRef Ident;2229if (Base.is<TypeInfoLValue>())2230InvalidBaseKind = 0;2231else if (isa_and_nonnull<StringLiteral>(BaseE))2232InvalidBaseKind = 1;2233else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||2234isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))2235InvalidBaseKind = 2;2236else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {2237InvalidBaseKind = 3;2238Ident = PE->getIdentKindName();2239}22402241if (InvalidBaseKind != -1) {2242Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)2243<< IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind2244<< Ident;2245return false;2246}2247}22482249if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);2250FD && FD->isImmediateFunction()) {2251Info.FFDiag(Loc, diag::note_consteval_address_accessible)2252<< !Type->isAnyPointerType();2253Info.Note(FD->getLocation(), diag::note_declared_at);2254return false;2255}22562257// Check that the object is a global. Note that the fake 'this' object we2258// manufacture when checking potential constant expressions is conservatively2259// assumed to be global here.2260if (!IsGlobalLValue(Base)) {2261if (Info.getLangOpts().CPlusPlus11) {2262Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)2263<< IsReferenceType << !Designator.Entries.empty() << !!BaseVD2264<< BaseVD;2265auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);2266if (VarD && VarD->isConstexpr()) {2267// Non-static local constexpr variables have unintuitive semantics:2268// constexpr int a = 1;2269// constexpr const int *p = &a;2270// ... is invalid because the address of 'a' is not constant. Suggest2271// adding a 'static' in this case.2272Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)2273<< VarD2274<< FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");2275} else {2276NoteLValueLocation(Info, Base);2277}2278} else {2279Info.FFDiag(Loc);2280}2281// Don't allow references to temporaries to escape.2282return false;2283}2284assert((Info.checkingPotentialConstantExpression() ||2285LVal.getLValueCallIndex() == 0) &&2286"have call index for global lvalue");22872288if (Base.is<DynamicAllocLValue>()) {2289Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)2290<< IsReferenceType << !Designator.Entries.empty();2291NoteLValueLocation(Info, Base);2292return false;2293}22942295if (BaseVD) {2296if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {2297// Check if this is a thread-local variable.2298if (Var->getTLSKind())2299// FIXME: Diagnostic!2300return false;23012302// A dllimport variable never acts like a constant, unless we're2303// evaluating a value for use only in name mangling.2304if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())2305// FIXME: Diagnostic!2306return false;23072308// In CUDA/HIP device compilation, only device side variables have2309// constant addresses.2310if (Info.getCtx().getLangOpts().CUDA &&2311Info.getCtx().getLangOpts().CUDAIsDevice &&2312Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {2313if ((!Var->hasAttr<CUDADeviceAttr>() &&2314!Var->hasAttr<CUDAConstantAttr>() &&2315!Var->getType()->isCUDADeviceBuiltinSurfaceType() &&2316!Var->getType()->isCUDADeviceBuiltinTextureType()) ||2317Var->hasAttr<HIPManagedAttr>())2318return false;2319}2320}2321if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {2322// __declspec(dllimport) must be handled very carefully:2323// We must never initialize an expression with the thunk in C++.2324// Doing otherwise would allow the same id-expression to yield2325// different addresses for the same function in different translation2326// units. However, this means that we must dynamically initialize the2327// expression with the contents of the import address table at runtime.2328//2329// The C language has no notion of ODR; furthermore, it has no notion of2330// dynamic initialization. This means that we are permitted to2331// perform initialization with the address of the thunk.2332if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&2333FD->hasAttr<DLLImportAttr>())2334// FIXME: Diagnostic!2335return false;2336}2337} else if (const auto *MTE =2338dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {2339if (CheckedTemps.insert(MTE).second) {2340QualType TempType = getType(Base);2341if (TempType.isDestructedType()) {2342Info.FFDiag(MTE->getExprLoc(),2343diag::note_constexpr_unsupported_temporary_nontrivial_dtor)2344<< TempType;2345return false;2346}23472348APValue *V = MTE->getOrCreateValue(false);2349assert(V && "evasluation result refers to uninitialised temporary");2350if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,2351Info, MTE->getExprLoc(), TempType, *V, Kind,2352/*SubobjectDecl=*/nullptr, CheckedTemps))2353return false;2354}2355}23562357// Allow address constant expressions to be past-the-end pointers. This is2358// an extension: the standard requires them to point to an object.2359if (!IsReferenceType)2360return true;23612362// A reference constant expression must refer to an object.2363if (!Base) {2364// FIXME: diagnostic2365Info.CCEDiag(Loc);2366return true;2367}23682369// Does this refer one past the end of some object?2370if (!Designator.Invalid && Designator.isOnePastTheEnd()) {2371Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)2372<< !Designator.Entries.empty() << !!BaseVD << BaseVD;2373NoteLValueLocation(Info, Base);2374}23752376return true;2377}23782379/// Member pointers are constant expressions unless they point to a2380/// non-virtual dllimport member function.2381static bool CheckMemberPointerConstantExpression(EvalInfo &Info,2382SourceLocation Loc,2383QualType Type,2384const APValue &Value,2385ConstantExprKind Kind) {2386const ValueDecl *Member = Value.getMemberPointerDecl();2387const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);2388if (!FD)2389return true;2390if (FD->isImmediateFunction()) {2391Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;2392Info.Note(FD->getLocation(), diag::note_declared_at);2393return false;2394}2395return isForManglingOnly(Kind) || FD->isVirtual() ||2396!FD->hasAttr<DLLImportAttr>();2397}23982399/// Check that this core constant expression is of literal type, and if not,2400/// produce an appropriate diagnostic.2401static bool CheckLiteralType(EvalInfo &Info, const Expr *E,2402const LValue *This = nullptr) {2403if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))2404return true;24052406// C++1y: A constant initializer for an object o [...] may also invoke2407// constexpr constructors for o and its subobjects even if those objects2408// are of non-literal class types.2409//2410// C++11 missed this detail for aggregates, so classes like this:2411// struct foo_t { union { int i; volatile int j; } u; };2412// are not (obviously) initializable like so:2413// __attribute__((__require_constant_initialization__))2414// static const foo_t x = {{0}};2415// because "i" is a subobject with non-literal initialization (due to the2416// volatile member of the union). See:2417// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#16772418// Therefore, we use the C++1y behavior.2419if (This && Info.EvaluatingDecl == This->getLValueBase())2420return true;24212422// Prvalue constant expressions must be of literal types.2423if (Info.getLangOpts().CPlusPlus11)2424Info.FFDiag(E, diag::note_constexpr_nonliteral)2425<< E->getType();2426else2427Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);2428return false;2429}24302431static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,2432EvalInfo &Info, SourceLocation DiagLoc,2433QualType Type, const APValue &Value,2434ConstantExprKind Kind,2435const FieldDecl *SubobjectDecl,2436CheckedTemporaries &CheckedTemps) {2437if (!Value.hasValue()) {2438if (SubobjectDecl) {2439Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)2440<< /*(name)*/ 1 << SubobjectDecl;2441Info.Note(SubobjectDecl->getLocation(),2442diag::note_constexpr_subobject_declared_here);2443} else {2444Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)2445<< /*of type*/ 0 << Type;2446}2447return false;2448}24492450// We allow _Atomic(T) to be initialized from anything that T can be2451// initialized from.2452if (const AtomicType *AT = Type->getAs<AtomicType>())2453Type = AT->getValueType();24542455// Core issue 1454: For a literal constant expression of array or class type,2456// each subobject of its value shall have been initialized by a constant2457// expression.2458if (Value.isArray()) {2459QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();2460for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {2461if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,2462Value.getArrayInitializedElt(I), Kind,2463SubobjectDecl, CheckedTemps))2464return false;2465}2466if (!Value.hasArrayFiller())2467return true;2468return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,2469Value.getArrayFiller(), Kind, SubobjectDecl,2470CheckedTemps);2471}2472if (Value.isUnion() && Value.getUnionField()) {2473return CheckEvaluationResult(2474CERK, Info, DiagLoc, Value.getUnionField()->getType(),2475Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);2476}2477if (Value.isStruct()) {2478RecordDecl *RD = Type->castAs<RecordType>()->getDecl();2479if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {2480unsigned BaseIndex = 0;2481for (const CXXBaseSpecifier &BS : CD->bases()) {2482const APValue &BaseValue = Value.getStructBase(BaseIndex);2483if (!BaseValue.hasValue()) {2484SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();2485Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)2486<< BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());2487return false;2488}2489if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,2490Kind, /*SubobjectDecl=*/nullptr,2491CheckedTemps))2492return false;2493++BaseIndex;2494}2495}2496for (const auto *I : RD->fields()) {2497if (I->isUnnamedBitField())2498continue;24992500if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),2501Value.getStructField(I->getFieldIndex()), Kind,2502I, CheckedTemps))2503return false;2504}2505}25062507if (Value.isLValue() &&2508CERK == CheckEvaluationResultKind::ConstantExpression) {2509LValue LVal;2510LVal.setFrom(Info.Ctx, Value);2511return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,2512CheckedTemps);2513}25142515if (Value.isMemberPointer() &&2516CERK == CheckEvaluationResultKind::ConstantExpression)2517return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);25182519// Everything else is fine.2520return true;2521}25222523/// Check that this core constant expression value is a valid value for a2524/// constant expression. If not, report an appropriate diagnostic. Does not2525/// check that the expression is of literal type.2526static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,2527QualType Type, const APValue &Value,2528ConstantExprKind Kind) {2529// Nothing to check for a constant expression of type 'cv void'.2530if (Type->isVoidType())2531return true;25322533CheckedTemporaries CheckedTemps;2534return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,2535Info, DiagLoc, Type, Value, Kind,2536/*SubobjectDecl=*/nullptr, CheckedTemps);2537}25382539/// Check that this evaluated value is fully-initialized and can be loaded by2540/// an lvalue-to-rvalue conversion.2541static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,2542QualType Type, const APValue &Value) {2543CheckedTemporaries CheckedTemps;2544return CheckEvaluationResult(2545CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,2546ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);2547}25482549/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless2550/// "the allocated storage is deallocated within the evaluation".2551static bool CheckMemoryLeaks(EvalInfo &Info) {2552if (!Info.HeapAllocs.empty()) {2553// We can still fold to a constant despite a compile-time memory leak,2554// so long as the heap allocation isn't referenced in the result (we check2555// that in CheckConstantExpression).2556Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,2557diag::note_constexpr_memory_leak)2558<< unsigned(Info.HeapAllocs.size() - 1);2559}2560return true;2561}25622563static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {2564// A null base expression indicates a null pointer. These are always2565// evaluatable, and they are false unless the offset is zero.2566if (!Value.getLValueBase()) {2567// TODO: Should a non-null pointer with an offset of zero evaluate to true?2568Result = !Value.getLValueOffset().isZero();2569return true;2570}25712572// We have a non-null base. These are generally known to be true, but if it's2573// a weak declaration it can be null at runtime.2574Result = true;2575const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();2576return !Decl || !Decl->isWeak();2577}25782579static bool HandleConversionToBool(const APValue &Val, bool &Result) {2580// TODO: This function should produce notes if it fails.2581switch (Val.getKind()) {2582case APValue::None:2583case APValue::Indeterminate:2584return false;2585case APValue::Int:2586Result = Val.getInt().getBoolValue();2587return true;2588case APValue::FixedPoint:2589Result = Val.getFixedPoint().getBoolValue();2590return true;2591case APValue::Float:2592Result = !Val.getFloat().isZero();2593return true;2594case APValue::ComplexInt:2595Result = Val.getComplexIntReal().getBoolValue() ||2596Val.getComplexIntImag().getBoolValue();2597return true;2598case APValue::ComplexFloat:2599Result = !Val.getComplexFloatReal().isZero() ||2600!Val.getComplexFloatImag().isZero();2601return true;2602case APValue::LValue:2603return EvalPointerValueAsBool(Val, Result);2604case APValue::MemberPointer:2605if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {2606return false;2607}2608Result = Val.getMemberPointerDecl();2609return true;2610case APValue::Vector:2611case APValue::Array:2612case APValue::Struct:2613case APValue::Union:2614case APValue::AddrLabelDiff:2615return false;2616}26172618llvm_unreachable("unknown APValue kind");2619}26202621static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,2622EvalInfo &Info) {2623assert(!E->isValueDependent());2624assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");2625APValue Val;2626if (!Evaluate(Val, Info, E))2627return false;2628return HandleConversionToBool(Val, Result);2629}26302631template<typename T>2632static bool HandleOverflow(EvalInfo &Info, const Expr *E,2633const T &SrcValue, QualType DestType) {2634Info.CCEDiag(E, diag::note_constexpr_overflow)2635<< SrcValue << DestType;2636return Info.noteUndefinedBehavior();2637}26382639static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,2640QualType SrcType, const APFloat &Value,2641QualType DestType, APSInt &Result) {2642unsigned DestWidth = Info.Ctx.getIntWidth(DestType);2643// Determine whether we are converting to unsigned or signed.2644bool DestSigned = DestType->isSignedIntegerOrEnumerationType();26452646Result = APSInt(DestWidth, !DestSigned);2647bool ignored;2648if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)2649& APFloat::opInvalidOp)2650return HandleOverflow(Info, E, Value, DestType);2651return true;2652}26532654/// Get rounding mode to use in evaluation of the specified expression.2655///2656/// If rounding mode is unknown at compile time, still try to evaluate the2657/// expression. If the result is exact, it does not depend on rounding mode.2658/// So return "tonearest" mode instead of "dynamic".2659static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {2660llvm::RoundingMode RM =2661E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();2662if (RM == llvm::RoundingMode::Dynamic)2663RM = llvm::RoundingMode::NearestTiesToEven;2664return RM;2665}26662667/// Check if the given evaluation result is allowed for constant evaluation.2668static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,2669APFloat::opStatus St) {2670// In a constant context, assume that any dynamic rounding mode or FP2671// exception state matches the default floating-point environment.2672if (Info.InConstantContext)2673return true;26742675FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());2676if ((St & APFloat::opInexact) &&2677FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {2678// Inexact result means that it depends on rounding mode. If the requested2679// mode is dynamic, the evaluation cannot be made in compile time.2680Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);2681return false;2682}26832684if ((St != APFloat::opOK) &&2685(FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||2686FPO.getExceptionMode() != LangOptions::FPE_Ignore ||2687FPO.getAllowFEnvAccess())) {2688Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);2689return false;2690}26912692if ((St & APFloat::opStatus::opInvalidOp) &&2693FPO.getExceptionMode() != LangOptions::FPE_Ignore) {2694// There is no usefully definable result.2695Info.FFDiag(E);2696return false;2697}26982699// FIXME: if:2700// - evaluation triggered other FP exception, and2701// - exception mode is not "ignore", and2702// - the expression being evaluated is not a part of global variable2703// initializer,2704// the evaluation probably need to be rejected.2705return true;2706}27072708static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,2709QualType SrcType, QualType DestType,2710APFloat &Result) {2711assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||2712isa<ConvertVectorExpr>(E)) &&2713"HandleFloatToFloatCast has been checked with only CastExpr, "2714"CompoundAssignOperator and ConvertVectorExpr. Please either validate "2715"the new expression or address the root cause of this usage.");2716llvm::RoundingMode RM = getActiveRoundingMode(Info, E);2717APFloat::opStatus St;2718APFloat Value = Result;2719bool ignored;2720St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);2721return checkFloatingPointResult(Info, E, St);2722}27232724static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,2725QualType DestType, QualType SrcType,2726const APSInt &Value) {2727unsigned DestWidth = Info.Ctx.getIntWidth(DestType);2728// Figure out if this is a truncate, extend or noop cast.2729// If the input is signed, do a sign extend, noop, or truncate.2730APSInt Result = Value.extOrTrunc(DestWidth);2731Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());2732if (DestType->isBooleanType())2733Result = Value.getBoolValue();2734return Result;2735}27362737static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,2738const FPOptions FPO,2739QualType SrcType, const APSInt &Value,2740QualType DestType, APFloat &Result) {2741Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);2742llvm::RoundingMode RM = getActiveRoundingMode(Info, E);2743APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);2744return checkFloatingPointResult(Info, E, St);2745}27462747static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,2748APValue &Value, const FieldDecl *FD) {2749assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");27502751if (!Value.isInt()) {2752// Trying to store a pointer-cast-to-integer into a bitfield.2753// FIXME: In this case, we should provide the diagnostic for casting2754// a pointer to an integer.2755assert(Value.isLValue() && "integral value neither int nor lvalue?");2756Info.FFDiag(E);2757return false;2758}27592760APSInt &Int = Value.getInt();2761unsigned OldBitWidth = Int.getBitWidth();2762unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);2763if (NewBitWidth < OldBitWidth)2764Int = Int.trunc(NewBitWidth).extend(OldBitWidth);2765return true;2766}27672768/// Perform the given integer operation, which is known to need at most BitWidth2769/// bits, and check for overflow in the original type (if that type was not an2770/// unsigned type).2771template<typename Operation>2772static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,2773const APSInt &LHS, const APSInt &RHS,2774unsigned BitWidth, Operation Op,2775APSInt &Result) {2776if (LHS.isUnsigned()) {2777Result = Op(LHS, RHS);2778return true;2779}27802781APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);2782Result = Value.trunc(LHS.getBitWidth());2783if (Result.extend(BitWidth) != Value) {2784if (Info.checkingForUndefinedBehavior())2785Info.Ctx.getDiagnostics().Report(E->getExprLoc(),2786diag::warn_integer_constant_overflow)2787<< toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,2788/*UpperCase=*/true, /*InsertSeparators=*/true)2789<< E->getType() << E->getSourceRange();2790return HandleOverflow(Info, E, Value, E->getType());2791}2792return true;2793}27942795/// Perform the given binary integer operation.2796static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,2797const APSInt &LHS, BinaryOperatorKind Opcode,2798APSInt RHS, APSInt &Result) {2799bool HandleOverflowResult = true;2800switch (Opcode) {2801default:2802Info.FFDiag(E);2803return false;2804case BO_Mul:2805return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,2806std::multiplies<APSInt>(), Result);2807case BO_Add:2808return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,2809std::plus<APSInt>(), Result);2810case BO_Sub:2811return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,2812std::minus<APSInt>(), Result);2813case BO_And: Result = LHS & RHS; return true;2814case BO_Xor: Result = LHS ^ RHS; return true;2815case BO_Or: Result = LHS | RHS; return true;2816case BO_Div:2817case BO_Rem:2818if (RHS == 0) {2819Info.FFDiag(E, diag::note_expr_divide_by_zero)2820<< E->getRHS()->getSourceRange();2821return false;2822}2823// Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports2824// this operation and gives the two's complement result.2825if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&2826LHS.isMinSignedValue())2827HandleOverflowResult = HandleOverflow(2828Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());2829Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);2830return HandleOverflowResult;2831case BO_Shl: {2832if (Info.getLangOpts().OpenCL)2833// OpenCL 6.3j: shift values are effectively % word size of LHS.2834RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),2835static_cast<uint64_t>(LHS.getBitWidth() - 1)),2836RHS.isUnsigned());2837else if (RHS.isSigned() && RHS.isNegative()) {2838// During constant-folding, a negative shift is an opposite shift. Such2839// a shift is not a constant expression.2840Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;2841if (!Info.noteUndefinedBehavior())2842return false;2843RHS = -RHS;2844goto shift_right;2845}2846shift_left:2847// C++11 [expr.shift]p1: Shift width must be less than the bit width of2848// the shifted type.2849unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);2850if (SA != RHS) {2851Info.CCEDiag(E, diag::note_constexpr_large_shift)2852<< RHS << E->getType() << LHS.getBitWidth();2853if (!Info.noteUndefinedBehavior())2854return false;2855} else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {2856// C++11 [expr.shift]p2: A signed left shift must have a non-negative2857// operand, and must not overflow the corresponding unsigned type.2858// C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to2859// E1 x 2^E2 module 2^N.2860if (LHS.isNegative()) {2861Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;2862if (!Info.noteUndefinedBehavior())2863return false;2864} else if (LHS.countl_zero() < SA) {2865Info.CCEDiag(E, diag::note_constexpr_lshift_discards);2866if (!Info.noteUndefinedBehavior())2867return false;2868}2869}2870Result = LHS << SA;2871return true;2872}2873case BO_Shr: {2874if (Info.getLangOpts().OpenCL)2875// OpenCL 6.3j: shift values are effectively % word size of LHS.2876RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),2877static_cast<uint64_t>(LHS.getBitWidth() - 1)),2878RHS.isUnsigned());2879else if (RHS.isSigned() && RHS.isNegative()) {2880// During constant-folding, a negative shift is an opposite shift. Such a2881// shift is not a constant expression.2882Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;2883if (!Info.noteUndefinedBehavior())2884return false;2885RHS = -RHS;2886goto shift_left;2887}2888shift_right:2889// C++11 [expr.shift]p1: Shift width must be less than the bit width of the2890// shifted type.2891unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);2892if (SA != RHS) {2893Info.CCEDiag(E, diag::note_constexpr_large_shift)2894<< RHS << E->getType() << LHS.getBitWidth();2895if (!Info.noteUndefinedBehavior())2896return false;2897}28982899Result = LHS >> SA;2900return true;2901}29022903case BO_LT: Result = LHS < RHS; return true;2904case BO_GT: Result = LHS > RHS; return true;2905case BO_LE: Result = LHS <= RHS; return true;2906case BO_GE: Result = LHS >= RHS; return true;2907case BO_EQ: Result = LHS == RHS; return true;2908case BO_NE: Result = LHS != RHS; return true;2909case BO_Cmp:2910llvm_unreachable("BO_Cmp should be handled elsewhere");2911}2912}29132914/// Perform the given binary floating-point operation, in-place, on LHS.2915static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,2916APFloat &LHS, BinaryOperatorKind Opcode,2917const APFloat &RHS) {2918llvm::RoundingMode RM = getActiveRoundingMode(Info, E);2919APFloat::opStatus St;2920switch (Opcode) {2921default:2922Info.FFDiag(E);2923return false;2924case BO_Mul:2925St = LHS.multiply(RHS, RM);2926break;2927case BO_Add:2928St = LHS.add(RHS, RM);2929break;2930case BO_Sub:2931St = LHS.subtract(RHS, RM);2932break;2933case BO_Div:2934// [expr.mul]p4:2935// If the second operand of / or % is zero the behavior is undefined.2936if (RHS.isZero())2937Info.CCEDiag(E, diag::note_expr_divide_by_zero);2938St = LHS.divide(RHS, RM);2939break;2940}29412942// [expr.pre]p4:2943// If during the evaluation of an expression, the result is not2944// mathematically defined [...], the behavior is undefined.2945// FIXME: C++ rules require us to not conform to IEEE 754 here.2946if (LHS.isNaN()) {2947Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();2948return Info.noteUndefinedBehavior();2949}29502951return checkFloatingPointResult(Info, E, St);2952}29532954static bool handleLogicalOpForVector(const APInt &LHSValue,2955BinaryOperatorKind Opcode,2956const APInt &RHSValue, APInt &Result) {2957bool LHS = (LHSValue != 0);2958bool RHS = (RHSValue != 0);29592960if (Opcode == BO_LAnd)2961Result = LHS && RHS;2962else2963Result = LHS || RHS;2964return true;2965}2966static bool handleLogicalOpForVector(const APFloat &LHSValue,2967BinaryOperatorKind Opcode,2968const APFloat &RHSValue, APInt &Result) {2969bool LHS = !LHSValue.isZero();2970bool RHS = !RHSValue.isZero();29712972if (Opcode == BO_LAnd)2973Result = LHS && RHS;2974else2975Result = LHS || RHS;2976return true;2977}29782979static bool handleLogicalOpForVector(const APValue &LHSValue,2980BinaryOperatorKind Opcode,2981const APValue &RHSValue, APInt &Result) {2982// The result is always an int type, however operands match the first.2983if (LHSValue.getKind() == APValue::Int)2984return handleLogicalOpForVector(LHSValue.getInt(), Opcode,2985RHSValue.getInt(), Result);2986assert(LHSValue.getKind() == APValue::Float && "Should be no other options");2987return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,2988RHSValue.getFloat(), Result);2989}29902991template <typename APTy>2992static bool2993handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,2994const APTy &RHSValue, APInt &Result) {2995switch (Opcode) {2996default:2997llvm_unreachable("unsupported binary operator");2998case BO_EQ:2999Result = (LHSValue == RHSValue);3000break;3001case BO_NE:3002Result = (LHSValue != RHSValue);3003break;3004case BO_LT:3005Result = (LHSValue < RHSValue);3006break;3007case BO_GT:3008Result = (LHSValue > RHSValue);3009break;3010case BO_LE:3011Result = (LHSValue <= RHSValue);3012break;3013case BO_GE:3014Result = (LHSValue >= RHSValue);3015break;3016}30173018// The boolean operations on these vector types use an instruction that3019// results in a mask of '-1' for the 'truth' value. Ensure that we negate 13020// to -1 to make sure that we produce the correct value.3021Result.negate();30223023return true;3024}30253026static bool handleCompareOpForVector(const APValue &LHSValue,3027BinaryOperatorKind Opcode,3028const APValue &RHSValue, APInt &Result) {3029// The result is always an int type, however operands match the first.3030if (LHSValue.getKind() == APValue::Int)3031return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,3032RHSValue.getInt(), Result);3033assert(LHSValue.getKind() == APValue::Float && "Should be no other options");3034return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,3035RHSValue.getFloat(), Result);3036}30373038// Perform binary operations for vector types, in place on the LHS.3039static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,3040BinaryOperatorKind Opcode,3041APValue &LHSValue,3042const APValue &RHSValue) {3043assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&3044"Operation not supported on vector types");30453046const auto *VT = E->getType()->castAs<VectorType>();3047unsigned NumElements = VT->getNumElements();3048QualType EltTy = VT->getElementType();30493050// In the cases (typically C as I've observed) where we aren't evaluating3051// constexpr but are checking for cases where the LHS isn't yet evaluatable,3052// just give up.3053if (!LHSValue.isVector()) {3054assert(LHSValue.isLValue() &&3055"A vector result that isn't a vector OR uncalculated LValue");3056Info.FFDiag(E);3057return false;3058}30593060assert(LHSValue.getVectorLength() == NumElements &&3061RHSValue.getVectorLength() == NumElements && "Different vector sizes");30623063SmallVector<APValue, 4> ResultElements;30643065for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {3066APValue LHSElt = LHSValue.getVectorElt(EltNum);3067APValue RHSElt = RHSValue.getVectorElt(EltNum);30683069if (EltTy->isIntegerType()) {3070APSInt EltResult{Info.Ctx.getIntWidth(EltTy),3071EltTy->isUnsignedIntegerType()};3072bool Success = true;30733074if (BinaryOperator::isLogicalOp(Opcode))3075Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);3076else if (BinaryOperator::isComparisonOp(Opcode))3077Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);3078else3079Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,3080RHSElt.getInt(), EltResult);30813082if (!Success) {3083Info.FFDiag(E);3084return false;3085}3086ResultElements.emplace_back(EltResult);30873088} else if (EltTy->isFloatingType()) {3089assert(LHSElt.getKind() == APValue::Float &&3090RHSElt.getKind() == APValue::Float &&3091"Mismatched LHS/RHS/Result Type");3092APFloat LHSFloat = LHSElt.getFloat();30933094if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,3095RHSElt.getFloat())) {3096Info.FFDiag(E);3097return false;3098}30993100ResultElements.emplace_back(LHSFloat);3101}3102}31033104LHSValue = APValue(ResultElements.data(), ResultElements.size());3105return true;3106}31073108/// Cast an lvalue referring to a base subobject to a derived class, by3109/// truncating the lvalue's path to the given length.3110static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,3111const RecordDecl *TruncatedType,3112unsigned TruncatedElements) {3113SubobjectDesignator &D = Result.Designator;31143115// Check we actually point to a derived class object.3116if (TruncatedElements == D.Entries.size())3117return true;3118assert(TruncatedElements >= D.MostDerivedPathLength &&3119"not casting to a derived class");3120if (!Result.checkSubobject(Info, E, CSK_Derived))3121return false;31223123// Truncate the path to the subobject, and remove any derived-to-base offsets.3124const RecordDecl *RD = TruncatedType;3125for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {3126if (RD->isInvalidDecl()) return false;3127const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);3128const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);3129if (isVirtualBaseClass(D.Entries[I]))3130Result.Offset -= Layout.getVBaseClassOffset(Base);3131else3132Result.Offset -= Layout.getBaseClassOffset(Base);3133RD = Base;3134}3135D.Entries.resize(TruncatedElements);3136return true;3137}31383139static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,3140const CXXRecordDecl *Derived,3141const CXXRecordDecl *Base,3142const ASTRecordLayout *RL = nullptr) {3143if (!RL) {3144if (Derived->isInvalidDecl()) return false;3145RL = &Info.Ctx.getASTRecordLayout(Derived);3146}31473148Obj.getLValueOffset() += RL->getBaseClassOffset(Base);3149Obj.addDecl(Info, E, Base, /*Virtual*/ false);3150return true;3151}31523153static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,3154const CXXRecordDecl *DerivedDecl,3155const CXXBaseSpecifier *Base) {3156const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();31573158if (!Base->isVirtual())3159return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);31603161SubobjectDesignator &D = Obj.Designator;3162if (D.Invalid)3163return false;31643165// Extract most-derived object and corresponding type.3166DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();3167if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))3168return false;31693170// Find the virtual base class.3171if (DerivedDecl->isInvalidDecl()) return false;3172const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);3173Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);3174Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);3175return true;3176}31773178static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,3179QualType Type, LValue &Result) {3180for (CastExpr::path_const_iterator PathI = E->path_begin(),3181PathE = E->path_end();3182PathI != PathE; ++PathI) {3183if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),3184*PathI))3185return false;3186Type = (*PathI)->getType();3187}3188return true;3189}31903191/// Cast an lvalue referring to a derived class to a known base subobject.3192static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,3193const CXXRecordDecl *DerivedRD,3194const CXXRecordDecl *BaseRD) {3195CXXBasePaths Paths(/*FindAmbiguities=*/false,3196/*RecordPaths=*/true, /*DetectVirtual=*/false);3197if (!DerivedRD->isDerivedFrom(BaseRD, Paths))3198llvm_unreachable("Class must be derived from the passed in base class!");31993200for (CXXBasePathElement &Elem : Paths.front())3201if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))3202return false;3203return true;3204}32053206/// Update LVal to refer to the given field, which must be a member of the type3207/// currently described by LVal.3208static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,3209const FieldDecl *FD,3210const ASTRecordLayout *RL = nullptr) {3211if (!RL) {3212if (FD->getParent()->isInvalidDecl()) return false;3213RL = &Info.Ctx.getASTRecordLayout(FD->getParent());3214}32153216unsigned I = FD->getFieldIndex();3217LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));3218LVal.addDecl(Info, E, FD);3219return true;3220}32213222/// Update LVal to refer to the given indirect field.3223static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,3224LValue &LVal,3225const IndirectFieldDecl *IFD) {3226for (const auto *C : IFD->chain())3227if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))3228return false;3229return true;3230}32313232enum class SizeOfType {3233SizeOf,3234DataSizeOf,3235};32363237/// Get the size of the given type in char units.3238static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,3239CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {3240// sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc3241// extension.3242if (Type->isVoidType() || Type->isFunctionType()) {3243Size = CharUnits::One();3244return true;3245}32463247if (Type->isDependentType()) {3248Info.FFDiag(Loc);3249return false;3250}32513252if (!Type->isConstantSizeType()) {3253// sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.3254// FIXME: Better diagnostic.3255Info.FFDiag(Loc);3256return false;3257}32583259if (SOT == SizeOfType::SizeOf)3260Size = Info.Ctx.getTypeSizeInChars(Type);3261else3262Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;3263return true;3264}32653266/// Update a pointer value to model pointer arithmetic.3267/// \param Info - Information about the ongoing evaluation.3268/// \param E - The expression being evaluated, for diagnostic purposes.3269/// \param LVal - The pointer value to be updated.3270/// \param EltTy - The pointee type represented by LVal.3271/// \param Adjustment - The adjustment, in objects of type EltTy, to add.3272static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,3273LValue &LVal, QualType EltTy,3274APSInt Adjustment) {3275CharUnits SizeOfPointee;3276if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))3277return false;32783279LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);3280return true;3281}32823283static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,3284LValue &LVal, QualType EltTy,3285int64_t Adjustment) {3286return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,3287APSInt::get(Adjustment));3288}32893290/// Update an lvalue to refer to a component of a complex number.3291/// \param Info - Information about the ongoing evaluation.3292/// \param LVal - The lvalue to be updated.3293/// \param EltTy - The complex number's component type.3294/// \param Imag - False for the real component, true for the imaginary.3295static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,3296LValue &LVal, QualType EltTy,3297bool Imag) {3298if (Imag) {3299CharUnits SizeOfComponent;3300if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))3301return false;3302LVal.Offset += SizeOfComponent;3303}3304LVal.addComplex(Info, E, EltTy, Imag);3305return true;3306}33073308/// Try to evaluate the initializer for a variable declaration.3309///3310/// \param Info Information about the ongoing evaluation.3311/// \param E An expression to be used when printing diagnostics.3312/// \param VD The variable whose initializer should be obtained.3313/// \param Version The version of the variable within the frame.3314/// \param Frame The frame in which the variable was created. Must be null3315/// if this variable is not local to the evaluation.3316/// \param Result Filled in with a pointer to the value of the variable.3317static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,3318const VarDecl *VD, CallStackFrame *Frame,3319unsigned Version, APValue *&Result) {3320APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);33213322// If this is a local variable, dig out its value.3323if (Frame) {3324Result = Frame->getTemporary(VD, Version);3325if (Result)3326return true;33273328if (!isa<ParmVarDecl>(VD)) {3329// Assume variables referenced within a lambda's call operator that were3330// not declared within the call operator are captures and during checking3331// of a potential constant expression, assume they are unknown constant3332// expressions.3333assert(isLambdaCallOperator(Frame->Callee) &&3334(VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&3335"missing value for local variable");3336if (Info.checkingPotentialConstantExpression())3337return false;3338// FIXME: This diagnostic is bogus; we do support captures. Is this code3339// still reachable at all?3340Info.FFDiag(E->getBeginLoc(),3341diag::note_unimplemented_constexpr_lambda_feature_ast)3342<< "captures not currently allowed";3343return false;3344}3345}33463347// If we're currently evaluating the initializer of this declaration, use that3348// in-flight value.3349if (Info.EvaluatingDecl == Base) {3350Result = Info.EvaluatingDeclValue;3351return true;3352}33533354if (isa<ParmVarDecl>(VD)) {3355// Assume parameters of a potential constant expression are usable in3356// constant expressions.3357if (!Info.checkingPotentialConstantExpression() ||3358!Info.CurrentCall->Callee ||3359!Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {3360if (Info.getLangOpts().CPlusPlus11) {3361Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)3362<< VD;3363NoteLValueLocation(Info, Base);3364} else {3365Info.FFDiag(E);3366}3367}3368return false;3369}33703371if (E->isValueDependent())3372return false;33733374// Dig out the initializer, and use the declaration which it's attached to.3375// FIXME: We should eventually check whether the variable has a reachable3376// initializing declaration.3377const Expr *Init = VD->getAnyInitializer(VD);3378if (!Init) {3379// Don't diagnose during potential constant expression checking; an3380// initializer might be added later.3381if (!Info.checkingPotentialConstantExpression()) {3382Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)3383<< VD;3384NoteLValueLocation(Info, Base);3385}3386return false;3387}33883389if (Init->isValueDependent()) {3390// The DeclRefExpr is not value-dependent, but the variable it refers to3391// has a value-dependent initializer. This should only happen in3392// constant-folding cases, where the variable is not actually of a suitable3393// type for use in a constant expression (otherwise the DeclRefExpr would3394// have been value-dependent too), so diagnose that.3395assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));3396if (!Info.checkingPotentialConstantExpression()) {3397Info.FFDiag(E, Info.getLangOpts().CPlusPlus113398? diag::note_constexpr_ltor_non_constexpr3399: diag::note_constexpr_ltor_non_integral, 1)3400<< VD << VD->getType();3401NoteLValueLocation(Info, Base);3402}3403return false;3404}34053406// Check that we can fold the initializer. In C++, we will have already done3407// this in the cases where it matters for conformance.3408if (!VD->evaluateValue()) {3409Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;3410NoteLValueLocation(Info, Base);3411return false;3412}34133414// Check that the variable is actually usable in constant expressions. For a3415// const integral variable or a reference, we might have a non-constant3416// initializer that we can nonetheless evaluate the initializer for. Such3417// variables are not usable in constant expressions. In C++98, the3418// initializer also syntactically needs to be an ICE.3419//3420// FIXME: We don't diagnose cases that aren't potentially usable in constant3421// expressions here; doing so would regress diagnostics for things like3422// reading from a volatile constexpr variable.3423if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&3424VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||3425((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&3426!Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {3427Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;3428NoteLValueLocation(Info, Base);3429}34303431// Never use the initializer of a weak variable, not even for constant3432// folding. We can't be sure that this is the definition that will be used.3433if (VD->isWeak()) {3434Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;3435NoteLValueLocation(Info, Base);3436return false;3437}34383439Result = VD->getEvaluatedValue();3440return true;3441}34423443/// Get the base index of the given base class within an APValue representing3444/// the given derived class.3445static unsigned getBaseIndex(const CXXRecordDecl *Derived,3446const CXXRecordDecl *Base) {3447Base = Base->getCanonicalDecl();3448unsigned Index = 0;3449for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),3450E = Derived->bases_end(); I != E; ++I, ++Index) {3451if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)3452return Index;3453}34543455llvm_unreachable("base class missing from derived class's bases list");3456}34573458/// Extract the value of a character from a string literal.3459static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,3460uint64_t Index) {3461assert(!isa<SourceLocExpr>(Lit) &&3462"SourceLocExpr should have already been converted to a StringLiteral");34633464// FIXME: Support MakeStringConstant3465if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {3466std::string Str;3467Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);3468assert(Index <= Str.size() && "Index too large");3469return APSInt::getUnsigned(Str.c_str()[Index]);3470}34713472if (auto PE = dyn_cast<PredefinedExpr>(Lit))3473Lit = PE->getFunctionName();3474const StringLiteral *S = cast<StringLiteral>(Lit);3475const ConstantArrayType *CAT =3476Info.Ctx.getAsConstantArrayType(S->getType());3477assert(CAT && "string literal isn't an array");3478QualType CharType = CAT->getElementType();3479assert(CharType->isIntegerType() && "unexpected character type");3480APSInt Value(Info.Ctx.getTypeSize(CharType),3481CharType->isUnsignedIntegerType());3482if (Index < S->getLength())3483Value = S->getCodeUnit(Index);3484return Value;3485}34863487// Expand a string literal into an array of characters.3488//3489// FIXME: This is inefficient; we should probably introduce something similar3490// to the LLVM ConstantDataArray to make this cheaper.3491static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,3492APValue &Result,3493QualType AllocType = QualType()) {3494const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(3495AllocType.isNull() ? S->getType() : AllocType);3496assert(CAT && "string literal isn't an array");3497QualType CharType = CAT->getElementType();3498assert(CharType->isIntegerType() && "unexpected character type");34993500unsigned Elts = CAT->getZExtSize();3501Result = APValue(APValue::UninitArray(),3502std::min(S->getLength(), Elts), Elts);3503APSInt Value(Info.Ctx.getTypeSize(CharType),3504CharType->isUnsignedIntegerType());3505if (Result.hasArrayFiller())3506Result.getArrayFiller() = APValue(Value);3507for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {3508Value = S->getCodeUnit(I);3509Result.getArrayInitializedElt(I) = APValue(Value);3510}3511}35123513// Expand an array so that it has more than Index filled elements.3514static void expandArray(APValue &Array, unsigned Index) {3515unsigned Size = Array.getArraySize();3516assert(Index < Size);35173518// Always at least double the number of elements for which we store a value.3519unsigned OldElts = Array.getArrayInitializedElts();3520unsigned NewElts = std::max(Index+1, OldElts * 2);3521NewElts = std::min(Size, std::max(NewElts, 8u));35223523// Copy the data across.3524APValue NewValue(APValue::UninitArray(), NewElts, Size);3525for (unsigned I = 0; I != OldElts; ++I)3526NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));3527for (unsigned I = OldElts; I != NewElts; ++I)3528NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();3529if (NewValue.hasArrayFiller())3530NewValue.getArrayFiller() = Array.getArrayFiller();3531Array.swap(NewValue);3532}35333534/// Determine whether a type would actually be read by an lvalue-to-rvalue3535/// conversion. If it's of class type, we may assume that the copy operation3536/// is trivial. Note that this is never true for a union type with fields3537/// (because the copy always "reads" the active member) and always true for3538/// a non-class type.3539static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);3540static bool isReadByLvalueToRvalueConversion(QualType T) {3541CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();3542return !RD || isReadByLvalueToRvalueConversion(RD);3543}3544static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {3545// FIXME: A trivial copy of a union copies the object representation, even if3546// the union is empty.3547if (RD->isUnion())3548return !RD->field_empty();3549if (RD->isEmpty())3550return false;35513552for (auto *Field : RD->fields())3553if (!Field->isUnnamedBitField() &&3554isReadByLvalueToRvalueConversion(Field->getType()))3555return true;35563557for (auto &BaseSpec : RD->bases())3558if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))3559return true;35603561return false;3562}35633564/// Diagnose an attempt to read from any unreadable field within the specified3565/// type, which might be a class type.3566static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,3567QualType T) {3568CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();3569if (!RD)3570return false;35713572if (!RD->hasMutableFields())3573return false;35743575for (auto *Field : RD->fields()) {3576// If we're actually going to read this field in some way, then it can't3577// be mutable. If we're in a union, then assigning to a mutable field3578// (even an empty one) can change the active member, so that's not OK.3579// FIXME: Add core issue number for the union case.3580if (Field->isMutable() &&3581(RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {3582Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;3583Info.Note(Field->getLocation(), diag::note_declared_at);3584return true;3585}35863587if (diagnoseMutableFields(Info, E, AK, Field->getType()))3588return true;3589}35903591for (auto &BaseSpec : RD->bases())3592if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))3593return true;35943595// All mutable fields were empty, and thus not actually read.3596return false;3597}35983599static bool lifetimeStartedInEvaluation(EvalInfo &Info,3600APValue::LValueBase Base,3601bool MutableSubobject = false) {3602// A temporary or transient heap allocation we created.3603if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())3604return true;36053606switch (Info.IsEvaluatingDecl) {3607case EvalInfo::EvaluatingDeclKind::None:3608return false;36093610case EvalInfo::EvaluatingDeclKind::Ctor:3611// The variable whose initializer we're evaluating.3612if (Info.EvaluatingDecl == Base)3613return true;36143615// A temporary lifetime-extended by the variable whose initializer we're3616// evaluating.3617if (auto *BaseE = Base.dyn_cast<const Expr *>())3618if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))3619return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();3620return false;36213622case EvalInfo::EvaluatingDeclKind::Dtor:3623// C++2a [expr.const]p6:3624// [during constant destruction] the lifetime of a and its non-mutable3625// subobjects (but not its mutable subobjects) [are] considered to start3626// within e.3627if (MutableSubobject || Base != Info.EvaluatingDecl)3628return false;3629// FIXME: We can meaningfully extend this to cover non-const objects, but3630// we will need special handling: we should be able to access only3631// subobjects of such objects that are themselves declared const.3632QualType T = getType(Base);3633return T.isConstQualified() || T->isReferenceType();3634}36353636llvm_unreachable("unknown evaluating decl kind");3637}36383639static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,3640SourceLocation CallLoc = {}) {3641return Info.CheckArraySize(3642CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,3643CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),3644/*Diag=*/true);3645}36463647namespace {3648/// A handle to a complete object (an object that is not a subobject of3649/// another object).3650struct CompleteObject {3651/// The identity of the object.3652APValue::LValueBase Base;3653/// The value of the complete object.3654APValue *Value;3655/// The type of the complete object.3656QualType Type;36573658CompleteObject() : Value(nullptr) {}3659CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)3660: Base(Base), Value(Value), Type(Type) {}36613662bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {3663// If this isn't a "real" access (eg, if it's just accessing the type3664// info), allow it. We assume the type doesn't change dynamically for3665// subobjects of constexpr objects (even though we'd hit UB here if it3666// did). FIXME: Is this right?3667if (!isAnyAccess(AK))3668return true;36693670// In C++14 onwards, it is permitted to read a mutable member whose3671// lifetime began within the evaluation.3672// FIXME: Should we also allow this in C++11?3673if (!Info.getLangOpts().CPlusPlus14)3674return false;3675return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);3676}36773678explicit operator bool() const { return !Type.isNull(); }3679};3680} // end anonymous namespace36813682static QualType getSubobjectType(QualType ObjType, QualType SubobjType,3683bool IsMutable = false) {3684// C++ [basic.type.qualifier]p1:3685// - A const object is an object of type const T or a non-mutable subobject3686// of a const object.3687if (ObjType.isConstQualified() && !IsMutable)3688SubobjType.addConst();3689// - A volatile object is an object of type const T or a subobject of a3690// volatile object.3691if (ObjType.isVolatileQualified())3692SubobjType.addVolatile();3693return SubobjType;3694}36953696/// Find the designated sub-object of an rvalue.3697template<typename SubobjectHandler>3698typename SubobjectHandler::result_type3699findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,3700const SubobjectDesignator &Sub, SubobjectHandler &handler) {3701if (Sub.Invalid)3702// A diagnostic will have already been produced.3703return handler.failed();3704if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {3705if (Info.getLangOpts().CPlusPlus11)3706Info.FFDiag(E, Sub.isOnePastTheEnd()3707? diag::note_constexpr_access_past_end3708: diag::note_constexpr_access_unsized_array)3709<< handler.AccessKind;3710else3711Info.FFDiag(E);3712return handler.failed();3713}37143715APValue *O = Obj.Value;3716QualType ObjType = Obj.Type;3717const FieldDecl *LastField = nullptr;3718const FieldDecl *VolatileField = nullptr;37193720// Walk the designator's path to find the subobject.3721for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {3722// Reading an indeterminate value is undefined, but assigning over one is OK.3723if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||3724(O->isIndeterminate() &&3725!isValidIndeterminateAccess(handler.AccessKind))) {3726if (!Info.checkingPotentialConstantExpression())3727Info.FFDiag(E, diag::note_constexpr_access_uninit)3728<< handler.AccessKind << O->isIndeterminate()3729<< E->getSourceRange();3730return handler.failed();3731}37323733// C++ [class.ctor]p5, C++ [class.dtor]p5:3734// const and volatile semantics are not applied on an object under3735// {con,de}struction.3736if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&3737ObjType->isRecordType() &&3738Info.isEvaluatingCtorDtor(3739Obj.Base,3740llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=3741ConstructionPhase::None) {3742ObjType = Info.Ctx.getCanonicalType(ObjType);3743ObjType.removeLocalConst();3744ObjType.removeLocalVolatile();3745}37463747// If this is our last pass, check that the final object type is OK.3748if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {3749// Accesses to volatile objects are prohibited.3750if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {3751if (Info.getLangOpts().CPlusPlus) {3752int DiagKind;3753SourceLocation Loc;3754const NamedDecl *Decl = nullptr;3755if (VolatileField) {3756DiagKind = 2;3757Loc = VolatileField->getLocation();3758Decl = VolatileField;3759} else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {3760DiagKind = 1;3761Loc = VD->getLocation();3762Decl = VD;3763} else {3764DiagKind = 0;3765if (auto *E = Obj.Base.dyn_cast<const Expr *>())3766Loc = E->getExprLoc();3767}3768Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)3769<< handler.AccessKind << DiagKind << Decl;3770Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;3771} else {3772Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);3773}3774return handler.failed();3775}37763777// If we are reading an object of class type, there may still be more3778// things we need to check: if there are any mutable subobjects, we3779// cannot perform this read. (This only happens when performing a trivial3780// copy or assignment.)3781if (ObjType->isRecordType() &&3782!Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&3783diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))3784return handler.failed();3785}37863787if (I == N) {3788if (!handler.found(*O, ObjType))3789return false;37903791// If we modified a bit-field, truncate it to the right width.3792if (isModification(handler.AccessKind) &&3793LastField && LastField->isBitField() &&3794!truncateBitfieldValue(Info, E, *O, LastField))3795return false;37963797return true;3798}37993800LastField = nullptr;3801if (ObjType->isArrayType()) {3802// Next subobject is an array element.3803const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);3804assert(CAT && "vla in literal type?");3805uint64_t Index = Sub.Entries[I].getAsArrayIndex();3806if (CAT->getSize().ule(Index)) {3807// Note, it should not be possible to form a pointer with a valid3808// designator which points more than one past the end of the array.3809if (Info.getLangOpts().CPlusPlus11)3810Info.FFDiag(E, diag::note_constexpr_access_past_end)3811<< handler.AccessKind;3812else3813Info.FFDiag(E);3814return handler.failed();3815}38163817ObjType = CAT->getElementType();38183819if (O->getArrayInitializedElts() > Index)3820O = &O->getArrayInitializedElt(Index);3821else if (!isRead(handler.AccessKind)) {3822if (!CheckArraySize(Info, CAT, E->getExprLoc()))3823return handler.failed();38243825expandArray(*O, Index);3826O = &O->getArrayInitializedElt(Index);3827} else3828O = &O->getArrayFiller();3829} else if (ObjType->isAnyComplexType()) {3830// Next subobject is a complex number.3831uint64_t Index = Sub.Entries[I].getAsArrayIndex();3832if (Index > 1) {3833if (Info.getLangOpts().CPlusPlus11)3834Info.FFDiag(E, diag::note_constexpr_access_past_end)3835<< handler.AccessKind;3836else3837Info.FFDiag(E);3838return handler.failed();3839}38403841ObjType = getSubobjectType(3842ObjType, ObjType->castAs<ComplexType>()->getElementType());38433844assert(I == N - 1 && "extracting subobject of scalar?");3845if (O->isComplexInt()) {3846return handler.found(Index ? O->getComplexIntImag()3847: O->getComplexIntReal(), ObjType);3848} else {3849assert(O->isComplexFloat());3850return handler.found(Index ? O->getComplexFloatImag()3851: O->getComplexFloatReal(), ObjType);3852}3853} else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {3854if (Field->isMutable() &&3855!Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {3856Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)3857<< handler.AccessKind << Field;3858Info.Note(Field->getLocation(), diag::note_declared_at);3859return handler.failed();3860}38613862// Next subobject is a class, struct or union field.3863RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();3864if (RD->isUnion()) {3865const FieldDecl *UnionField = O->getUnionField();3866if (!UnionField ||3867UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {3868if (I == N - 1 && handler.AccessKind == AK_Construct) {3869// Placement new onto an inactive union member makes it active.3870O->setUnion(Field, APValue());3871} else {3872// FIXME: If O->getUnionValue() is absent, report that there's no3873// active union member rather than reporting the prior active union3874// member. We'll need to fix nullptr_t to not use APValue() as its3875// representation first.3876Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)3877<< handler.AccessKind << Field << !UnionField << UnionField;3878return handler.failed();3879}3880}3881O = &O->getUnionValue();3882} else3883O = &O->getStructField(Field->getFieldIndex());38843885ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());3886LastField = Field;3887if (Field->getType().isVolatileQualified())3888VolatileField = Field;3889} else {3890// Next subobject is a base class.3891const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();3892const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);3893O = &O->getStructBase(getBaseIndex(Derived, Base));38943895ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));3896}3897}3898}38993900namespace {3901struct ExtractSubobjectHandler {3902EvalInfo &Info;3903const Expr *E;3904APValue &Result;3905const AccessKinds AccessKind;39063907typedef bool result_type;3908bool failed() { return false; }3909bool found(APValue &Subobj, QualType SubobjType) {3910Result = Subobj;3911if (AccessKind == AK_ReadObjectRepresentation)3912return true;3913return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);3914}3915bool found(APSInt &Value, QualType SubobjType) {3916Result = APValue(Value);3917return true;3918}3919bool found(APFloat &Value, QualType SubobjType) {3920Result = APValue(Value);3921return true;3922}3923};3924} // end anonymous namespace39253926/// Extract the designated sub-object of an rvalue.3927static bool extractSubobject(EvalInfo &Info, const Expr *E,3928const CompleteObject &Obj,3929const SubobjectDesignator &Sub, APValue &Result,3930AccessKinds AK = AK_Read) {3931assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);3932ExtractSubobjectHandler Handler = {Info, E, Result, AK};3933return findSubobject(Info, E, Obj, Sub, Handler);3934}39353936namespace {3937struct ModifySubobjectHandler {3938EvalInfo &Info;3939APValue &NewVal;3940const Expr *E;39413942typedef bool result_type;3943static const AccessKinds AccessKind = AK_Assign;39443945bool checkConst(QualType QT) {3946// Assigning to a const object has undefined behavior.3947if (QT.isConstQualified()) {3948Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;3949return false;3950}3951return true;3952}39533954bool failed() { return false; }3955bool found(APValue &Subobj, QualType SubobjType) {3956if (!checkConst(SubobjType))3957return false;3958// We've been given ownership of NewVal, so just swap it in.3959Subobj.swap(NewVal);3960return true;3961}3962bool found(APSInt &Value, QualType SubobjType) {3963if (!checkConst(SubobjType))3964return false;3965if (!NewVal.isInt()) {3966// Maybe trying to write a cast pointer value into a complex?3967Info.FFDiag(E);3968return false;3969}3970Value = NewVal.getInt();3971return true;3972}3973bool found(APFloat &Value, QualType SubobjType) {3974if (!checkConst(SubobjType))3975return false;3976Value = NewVal.getFloat();3977return true;3978}3979};3980} // end anonymous namespace39813982const AccessKinds ModifySubobjectHandler::AccessKind;39833984/// Update the designated sub-object of an rvalue to the given value.3985static bool modifySubobject(EvalInfo &Info, const Expr *E,3986const CompleteObject &Obj,3987const SubobjectDesignator &Sub,3988APValue &NewVal) {3989ModifySubobjectHandler Handler = { Info, NewVal, E };3990return findSubobject(Info, E, Obj, Sub, Handler);3991}39923993/// Find the position where two subobject designators diverge, or equivalently3994/// the length of the common initial subsequence.3995static unsigned FindDesignatorMismatch(QualType ObjType,3996const SubobjectDesignator &A,3997const SubobjectDesignator &B,3998bool &WasArrayIndex) {3999unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());4000for (/**/; I != N; ++I) {4001if (!ObjType.isNull() &&4002(ObjType->isArrayType() || ObjType->isAnyComplexType())) {4003// Next subobject is an array element.4004if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {4005WasArrayIndex = true;4006return I;4007}4008if (ObjType->isAnyComplexType())4009ObjType = ObjType->castAs<ComplexType>()->getElementType();4010else4011ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();4012} else {4013if (A.Entries[I].getAsBaseOrMember() !=4014B.Entries[I].getAsBaseOrMember()) {4015WasArrayIndex = false;4016return I;4017}4018if (const FieldDecl *FD = getAsField(A.Entries[I]))4019// Next subobject is a field.4020ObjType = FD->getType();4021else4022// Next subobject is a base class.4023ObjType = QualType();4024}4025}4026WasArrayIndex = false;4027return I;4028}40294030/// Determine whether the given subobject designators refer to elements of the4031/// same array object.4032static bool AreElementsOfSameArray(QualType ObjType,4033const SubobjectDesignator &A,4034const SubobjectDesignator &B) {4035if (A.Entries.size() != B.Entries.size())4036return false;40374038bool IsArray = A.MostDerivedIsArrayElement;4039if (IsArray && A.MostDerivedPathLength != A.Entries.size())4040// A is a subobject of the array element.4041return false;40424043// If A (and B) designates an array element, the last entry will be the array4044// index. That doesn't have to match. Otherwise, we're in the 'implicit array4045// of length 1' case, and the entire path must match.4046bool WasArrayIndex;4047unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);4048return CommonLength >= A.Entries.size() - IsArray;4049}40504051/// Find the complete object to which an LValue refers.4052static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,4053AccessKinds AK, const LValue &LVal,4054QualType LValType) {4055if (LVal.InvalidBase) {4056Info.FFDiag(E);4057return CompleteObject();4058}40594060if (!LVal.Base) {4061Info.FFDiag(E, diag::note_constexpr_access_null) << AK;4062return CompleteObject();4063}40644065CallStackFrame *Frame = nullptr;4066unsigned Depth = 0;4067if (LVal.getLValueCallIndex()) {4068std::tie(Frame, Depth) =4069Info.getCallFrameAndDepth(LVal.getLValueCallIndex());4070if (!Frame) {4071Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)4072<< AK << LVal.Base.is<const ValueDecl*>();4073NoteLValueLocation(Info, LVal.Base);4074return CompleteObject();4075}4076}40774078bool IsAccess = isAnyAccess(AK);40794080// C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type4081// is not a constant expression (even if the object is non-volatile). We also4082// apply this rule to C++98, in order to conform to the expected 'volatile'4083// semantics.4084if (isFormalAccess(AK) && LValType.isVolatileQualified()) {4085if (Info.getLangOpts().CPlusPlus)4086Info.FFDiag(E, diag::note_constexpr_access_volatile_type)4087<< AK << LValType;4088else4089Info.FFDiag(E);4090return CompleteObject();4091}40924093// Compute value storage location and type of base object.4094APValue *BaseVal = nullptr;4095QualType BaseType = getType(LVal.Base);40964097if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&4098lifetimeStartedInEvaluation(Info, LVal.Base)) {4099// This is the object whose initializer we're evaluating, so its lifetime4100// started in the current evaluation.4101BaseVal = Info.EvaluatingDeclValue;4102} else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {4103// Allow reading from a GUID declaration.4104if (auto *GD = dyn_cast<MSGuidDecl>(D)) {4105if (isModification(AK)) {4106// All the remaining cases do not permit modification of the object.4107Info.FFDiag(E, diag::note_constexpr_modify_global);4108return CompleteObject();4109}4110APValue &V = GD->getAsAPValue();4111if (V.isAbsent()) {4112Info.FFDiag(E, diag::note_constexpr_unsupported_layout)4113<< GD->getType();4114return CompleteObject();4115}4116return CompleteObject(LVal.Base, &V, GD->getType());4117}41184119// Allow reading the APValue from an UnnamedGlobalConstantDecl.4120if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {4121if (isModification(AK)) {4122Info.FFDiag(E, diag::note_constexpr_modify_global);4123return CompleteObject();4124}4125return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),4126GCD->getType());4127}41284129// Allow reading from template parameter objects.4130if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {4131if (isModification(AK)) {4132Info.FFDiag(E, diag::note_constexpr_modify_global);4133return CompleteObject();4134}4135return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),4136TPO->getType());4137}41384139// In C++98, const, non-volatile integers initialized with ICEs are ICEs.4140// In C++11, constexpr, non-volatile variables initialized with constant4141// expressions are constant expressions too. Inside constexpr functions,4142// parameters are constant expressions even if they're non-const.4143// In C++1y, objects local to a constant expression (those with a Frame) are4144// both readable and writable inside constant expressions.4145// In C, such things can also be folded, although they are not ICEs.4146const VarDecl *VD = dyn_cast<VarDecl>(D);4147if (VD) {4148if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))4149VD = VDef;4150}4151if (!VD || VD->isInvalidDecl()) {4152Info.FFDiag(E);4153return CompleteObject();4154}41554156bool IsConstant = BaseType.isConstant(Info.Ctx);4157bool ConstexprVar = false;4158if (const auto *VD = dyn_cast_if_present<VarDecl>(4159Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))4160ConstexprVar = VD->isConstexpr();41614162// Unless we're looking at a local variable or argument in a constexpr call,4163// the variable we're reading must be const.4164if (!Frame) {4165if (IsAccess && isa<ParmVarDecl>(VD)) {4166// Access of a parameter that's not associated with a frame isn't going4167// to work out, but we can leave it to evaluateVarDeclInit to provide a4168// suitable diagnostic.4169} else if (Info.getLangOpts().CPlusPlus14 &&4170lifetimeStartedInEvaluation(Info, LVal.Base)) {4171// OK, we can read and modify an object if we're in the process of4172// evaluating its initializer, because its lifetime began in this4173// evaluation.4174} else if (isModification(AK)) {4175// All the remaining cases do not permit modification of the object.4176Info.FFDiag(E, diag::note_constexpr_modify_global);4177return CompleteObject();4178} else if (VD->isConstexpr()) {4179// OK, we can read this variable.4180} else if (Info.getLangOpts().C23 && ConstexprVar) {4181Info.FFDiag(E);4182return CompleteObject();4183} else if (BaseType->isIntegralOrEnumerationType()) {4184if (!IsConstant) {4185if (!IsAccess)4186return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);4187if (Info.getLangOpts().CPlusPlus) {4188Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;4189Info.Note(VD->getLocation(), diag::note_declared_at);4190} else {4191Info.FFDiag(E);4192}4193return CompleteObject();4194}4195} else if (!IsAccess) {4196return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);4197} else if (IsConstant && Info.checkingPotentialConstantExpression() &&4198BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {4199// This variable might end up being constexpr. Don't diagnose it yet.4200} else if (IsConstant) {4201// Keep evaluating to see what we can do. In particular, we support4202// folding of const floating-point types, in order to make static const4203// data members of such types (supported as an extension) more useful.4204if (Info.getLangOpts().CPlusPlus) {4205Info.CCEDiag(E, Info.getLangOpts().CPlusPlus114206? diag::note_constexpr_ltor_non_constexpr4207: diag::note_constexpr_ltor_non_integral, 1)4208<< VD << BaseType;4209Info.Note(VD->getLocation(), diag::note_declared_at);4210} else {4211Info.CCEDiag(E);4212}4213} else {4214// Never allow reading a non-const value.4215if (Info.getLangOpts().CPlusPlus) {4216Info.FFDiag(E, Info.getLangOpts().CPlusPlus114217? diag::note_constexpr_ltor_non_constexpr4218: diag::note_constexpr_ltor_non_integral, 1)4219<< VD << BaseType;4220Info.Note(VD->getLocation(), diag::note_declared_at);4221} else {4222Info.FFDiag(E);4223}4224return CompleteObject();4225}4226}42274228if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))4229return CompleteObject();4230} else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {4231std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);4232if (!Alloc) {4233Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;4234return CompleteObject();4235}4236return CompleteObject(LVal.Base, &(*Alloc)->Value,4237LVal.Base.getDynamicAllocType());4238} else {4239const Expr *Base = LVal.Base.dyn_cast<const Expr*>();42404241if (!Frame) {4242if (const MaterializeTemporaryExpr *MTE =4243dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {4244assert(MTE->getStorageDuration() == SD_Static &&4245"should have a frame for a non-global materialized temporary");42464247// C++20 [expr.const]p4: [DR2126]4248// An object or reference is usable in constant expressions if it is4249// - a temporary object of non-volatile const-qualified literal type4250// whose lifetime is extended to that of a variable that is usable4251// in constant expressions4252//4253// C++20 [expr.const]p5:4254// an lvalue-to-rvalue conversion [is not allowed unless it applies to]4255// - a non-volatile glvalue that refers to an object that is usable4256// in constant expressions, or4257// - a non-volatile glvalue of literal type that refers to a4258// non-volatile object whose lifetime began within the evaluation4259// of E;4260//4261// C++11 misses the 'began within the evaluation of e' check and4262// instead allows all temporaries, including things like:4263// int &&r = 1;4264// int x = ++r;4265// constexpr int k = r;4266// Therefore we use the C++14-onwards rules in C++11 too.4267//4268// Note that temporaries whose lifetimes began while evaluating a4269// variable's constructor are not usable while evaluating the4270// corresponding destructor, not even if they're of const-qualified4271// types.4272if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&4273!lifetimeStartedInEvaluation(Info, LVal.Base)) {4274if (!IsAccess)4275return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);4276Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;4277Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);4278return CompleteObject();4279}42804281BaseVal = MTE->getOrCreateValue(false);4282assert(BaseVal && "got reference to unevaluated temporary");4283} else {4284if (!IsAccess)4285return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);4286APValue Val;4287LVal.moveInto(Val);4288Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)4289<< AK4290<< Val.getAsString(Info.Ctx,4291Info.Ctx.getLValueReferenceType(LValType));4292NoteLValueLocation(Info, LVal.Base);4293return CompleteObject();4294}4295} else {4296BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());4297assert(BaseVal && "missing value for temporary");4298}4299}43004301// In C++14, we can't safely access any mutable state when we might be4302// evaluating after an unmodeled side effect. Parameters are modeled as state4303// in the caller, but aren't visible once the call returns, so they can be4304// modified in a speculatively-evaluated call.4305//4306// FIXME: Not all local state is mutable. Allow local constant subobjects4307// to be read here (but take care with 'mutable' fields).4308unsigned VisibleDepth = Depth;4309if (llvm::isa_and_nonnull<ParmVarDecl>(4310LVal.Base.dyn_cast<const ValueDecl *>()))4311++VisibleDepth;4312if ((Frame && Info.getLangOpts().CPlusPlus14 &&4313Info.EvalStatus.HasSideEffects) ||4314(isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))4315return CompleteObject();43164317return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);4318}43194320/// Perform an lvalue-to-rvalue conversion on the given glvalue. This4321/// can also be used for 'lvalue-to-lvalue' conversions for looking up the4322/// glvalue referred to by an entity of reference type.4323///4324/// \param Info - Information about the ongoing evaluation.4325/// \param Conv - The expression for which we are performing the conversion.4326/// Used for diagnostics.4327/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the4328/// case of a non-class type).4329/// \param LVal - The glvalue on which we are attempting to perform this action.4330/// \param RVal - The produced value will be placed here.4331/// \param WantObjectRepresentation - If true, we're looking for the object4332/// representation rather than the value, and in particular,4333/// there is no requirement that the result be fully initialized.4334static bool4335handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,4336const LValue &LVal, APValue &RVal,4337bool WantObjectRepresentation = false) {4338if (LVal.Designator.Invalid)4339return false;43404341// Check for special cases where there is no existing APValue to look at.4342const Expr *Base = LVal.Base.dyn_cast<const Expr*>();43434344AccessKinds AK =4345WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;43464347if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {4348if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {4349// In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the4350// initializer until now for such expressions. Such an expression can't be4351// an ICE in C, so this only matters for fold.4352if (Type.isVolatileQualified()) {4353Info.FFDiag(Conv);4354return false;4355}43564357APValue Lit;4358if (!Evaluate(Lit, Info, CLE->getInitializer()))4359return false;43604361// According to GCC info page:4362//4363// 6.28 Compound Literals4364//4365// As an optimization, G++ sometimes gives array compound literals longer4366// lifetimes: when the array either appears outside a function or has a4367// const-qualified type. If foo and its initializer had elements of type4368// char *const rather than char *, or if foo were a global variable, the4369// array would have static storage duration. But it is probably safest4370// just to avoid the use of array compound literals in C++ code.4371//4372// Obey that rule by checking constness for converted array types.43734374QualType CLETy = CLE->getType();4375if (CLETy->isArrayType() && !Type->isArrayType()) {4376if (!CLETy.isConstant(Info.Ctx)) {4377Info.FFDiag(Conv);4378Info.Note(CLE->getExprLoc(), diag::note_declared_at);4379return false;4380}4381}43824383CompleteObject LitObj(LVal.Base, &Lit, Base->getType());4384return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);4385} else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {4386// Special-case character extraction so we don't have to construct an4387// APValue for the whole string.4388assert(LVal.Designator.Entries.size() <= 1 &&4389"Can only read characters from string literals");4390if (LVal.Designator.Entries.empty()) {4391// Fail for now for LValue to RValue conversion of an array.4392// (This shouldn't show up in C/C++, but it could be triggered by a4393// weird EvaluateAsRValue call from a tool.)4394Info.FFDiag(Conv);4395return false;4396}4397if (LVal.Designator.isOnePastTheEnd()) {4398if (Info.getLangOpts().CPlusPlus11)4399Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;4400else4401Info.FFDiag(Conv);4402return false;4403}4404uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();4405RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));4406return true;4407}4408}44094410CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);4411return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);4412}44134414/// Perform an assignment of Val to LVal. Takes ownership of Val.4415static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,4416QualType LValType, APValue &Val) {4417if (LVal.Designator.Invalid)4418return false;44194420if (!Info.getLangOpts().CPlusPlus14) {4421Info.FFDiag(E);4422return false;4423}44244425CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);4426return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);4427}44284429namespace {4430struct CompoundAssignSubobjectHandler {4431EvalInfo &Info;4432const CompoundAssignOperator *E;4433QualType PromotedLHSType;4434BinaryOperatorKind Opcode;4435const APValue &RHS;44364437static const AccessKinds AccessKind = AK_Assign;44384439typedef bool result_type;44404441bool checkConst(QualType QT) {4442// Assigning to a const object has undefined behavior.4443if (QT.isConstQualified()) {4444Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;4445return false;4446}4447return true;4448}44494450bool failed() { return false; }4451bool found(APValue &Subobj, QualType SubobjType) {4452switch (Subobj.getKind()) {4453case APValue::Int:4454return found(Subobj.getInt(), SubobjType);4455case APValue::Float:4456return found(Subobj.getFloat(), SubobjType);4457case APValue::ComplexInt:4458case APValue::ComplexFloat:4459// FIXME: Implement complex compound assignment.4460Info.FFDiag(E);4461return false;4462case APValue::LValue:4463return foundPointer(Subobj, SubobjType);4464case APValue::Vector:4465return foundVector(Subobj, SubobjType);4466case APValue::Indeterminate:4467Info.FFDiag(E, diag::note_constexpr_access_uninit)4468<< /*read of=*/0 << /*uninitialized object=*/14469<< E->getLHS()->getSourceRange();4470return false;4471default:4472// FIXME: can this happen?4473Info.FFDiag(E);4474return false;4475}4476}44774478bool foundVector(APValue &Value, QualType SubobjType) {4479if (!checkConst(SubobjType))4480return false;44814482if (!SubobjType->isVectorType()) {4483Info.FFDiag(E);4484return false;4485}4486return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);4487}44884489bool found(APSInt &Value, QualType SubobjType) {4490if (!checkConst(SubobjType))4491return false;44924493if (!SubobjType->isIntegerType()) {4494// We don't support compound assignment on integer-cast-to-pointer4495// values.4496Info.FFDiag(E);4497return false;4498}44994500if (RHS.isInt()) {4501APSInt LHS =4502HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);4503if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))4504return false;4505Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);4506return true;4507} else if (RHS.isFloat()) {4508const FPOptions FPO = E->getFPFeaturesInEffect(4509Info.Ctx.getLangOpts());4510APFloat FValue(0.0);4511return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,4512PromotedLHSType, FValue) &&4513handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&4514HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,4515Value);4516}45174518Info.FFDiag(E);4519return false;4520}4521bool found(APFloat &Value, QualType SubobjType) {4522return checkConst(SubobjType) &&4523HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,4524Value) &&4525handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&4526HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);4527}4528bool foundPointer(APValue &Subobj, QualType SubobjType) {4529if (!checkConst(SubobjType))4530return false;45314532QualType PointeeType;4533if (const PointerType *PT = SubobjType->getAs<PointerType>())4534PointeeType = PT->getPointeeType();45354536if (PointeeType.isNull() || !RHS.isInt() ||4537(Opcode != BO_Add && Opcode != BO_Sub)) {4538Info.FFDiag(E);4539return false;4540}45414542APSInt Offset = RHS.getInt();4543if (Opcode == BO_Sub)4544negateAsSigned(Offset);45454546LValue LVal;4547LVal.setFrom(Info.Ctx, Subobj);4548if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))4549return false;4550LVal.moveInto(Subobj);4551return true;4552}4553};4554} // end anonymous namespace45554556const AccessKinds CompoundAssignSubobjectHandler::AccessKind;45574558/// Perform a compound assignment of LVal <op>= RVal.4559static bool handleCompoundAssignment(EvalInfo &Info,4560const CompoundAssignOperator *E,4561const LValue &LVal, QualType LValType,4562QualType PromotedLValType,4563BinaryOperatorKind Opcode,4564const APValue &RVal) {4565if (LVal.Designator.Invalid)4566return false;45674568if (!Info.getLangOpts().CPlusPlus14) {4569Info.FFDiag(E);4570return false;4571}45724573CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);4574CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,4575RVal };4576return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);4577}45784579namespace {4580struct IncDecSubobjectHandler {4581EvalInfo &Info;4582const UnaryOperator *E;4583AccessKinds AccessKind;4584APValue *Old;45854586typedef bool result_type;45874588bool checkConst(QualType QT) {4589// Assigning to a const object has undefined behavior.4590if (QT.isConstQualified()) {4591Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;4592return false;4593}4594return true;4595}45964597bool failed() { return false; }4598bool found(APValue &Subobj, QualType SubobjType) {4599// Stash the old value. Also clear Old, so we don't clobber it later4600// if we're post-incrementing a complex.4601if (Old) {4602*Old = Subobj;4603Old = nullptr;4604}46054606switch (Subobj.getKind()) {4607case APValue::Int:4608return found(Subobj.getInt(), SubobjType);4609case APValue::Float:4610return found(Subobj.getFloat(), SubobjType);4611case APValue::ComplexInt:4612return found(Subobj.getComplexIntReal(),4613SubobjType->castAs<ComplexType>()->getElementType()4614.withCVRQualifiers(SubobjType.getCVRQualifiers()));4615case APValue::ComplexFloat:4616return found(Subobj.getComplexFloatReal(),4617SubobjType->castAs<ComplexType>()->getElementType()4618.withCVRQualifiers(SubobjType.getCVRQualifiers()));4619case APValue::LValue:4620return foundPointer(Subobj, SubobjType);4621default:4622// FIXME: can this happen?4623Info.FFDiag(E);4624return false;4625}4626}4627bool found(APSInt &Value, QualType SubobjType) {4628if (!checkConst(SubobjType))4629return false;46304631if (!SubobjType->isIntegerType()) {4632// We don't support increment / decrement on integer-cast-to-pointer4633// values.4634Info.FFDiag(E);4635return false;4636}46374638if (Old) *Old = APValue(Value);46394640// bool arithmetic promotes to int, and the conversion back to bool4641// doesn't reduce mod 2^n, so special-case it.4642if (SubobjType->isBooleanType()) {4643if (AccessKind == AK_Increment)4644Value = 1;4645else4646Value = !Value;4647return true;4648}46494650bool WasNegative = Value.isNegative();4651if (AccessKind == AK_Increment) {4652++Value;46534654if (!WasNegative && Value.isNegative() && E->canOverflow()) {4655APSInt ActualValue(Value, /*IsUnsigned*/true);4656return HandleOverflow(Info, E, ActualValue, SubobjType);4657}4658} else {4659--Value;46604661if (WasNegative && !Value.isNegative() && E->canOverflow()) {4662unsigned BitWidth = Value.getBitWidth();4663APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);4664ActualValue.setBit(BitWidth);4665return HandleOverflow(Info, E, ActualValue, SubobjType);4666}4667}4668return true;4669}4670bool found(APFloat &Value, QualType SubobjType) {4671if (!checkConst(SubobjType))4672return false;46734674if (Old) *Old = APValue(Value);46754676APFloat One(Value.getSemantics(), 1);4677llvm::RoundingMode RM = getActiveRoundingMode(Info, E);4678APFloat::opStatus St;4679if (AccessKind == AK_Increment)4680St = Value.add(One, RM);4681else4682St = Value.subtract(One, RM);4683return checkFloatingPointResult(Info, E, St);4684}4685bool foundPointer(APValue &Subobj, QualType SubobjType) {4686if (!checkConst(SubobjType))4687return false;46884689QualType PointeeType;4690if (const PointerType *PT = SubobjType->getAs<PointerType>())4691PointeeType = PT->getPointeeType();4692else {4693Info.FFDiag(E);4694return false;4695}46964697LValue LVal;4698LVal.setFrom(Info.Ctx, Subobj);4699if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,4700AccessKind == AK_Increment ? 1 : -1))4701return false;4702LVal.moveInto(Subobj);4703return true;4704}4705};4706} // end anonymous namespace47074708/// Perform an increment or decrement on LVal.4709static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,4710QualType LValType, bool IsIncrement, APValue *Old) {4711if (LVal.Designator.Invalid)4712return false;47134714if (!Info.getLangOpts().CPlusPlus14) {4715Info.FFDiag(E);4716return false;4717}47184719AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;4720CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);4721IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};4722return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);4723}47244725/// Build an lvalue for the object argument of a member function call.4726static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,4727LValue &This) {4728if (Object->getType()->isPointerType() && Object->isPRValue())4729return EvaluatePointer(Object, This, Info);47304731if (Object->isGLValue())4732return EvaluateLValue(Object, This, Info);47334734if (Object->getType()->isLiteralType(Info.Ctx))4735return EvaluateTemporary(Object, This, Info);47364737if (Object->getType()->isRecordType() && Object->isPRValue())4738return EvaluateTemporary(Object, This, Info);47394740Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();4741return false;4742}47434744/// HandleMemberPointerAccess - Evaluate a member access operation and build an4745/// lvalue referring to the result.4746///4747/// \param Info - Information about the ongoing evaluation.4748/// \param LV - An lvalue referring to the base of the member pointer.4749/// \param RHS - The member pointer expression.4750/// \param IncludeMember - Specifies whether the member itself is included in4751/// the resulting LValue subobject designator. This is not possible when4752/// creating a bound member function.4753/// \return The field or method declaration to which the member pointer refers,4754/// or 0 if evaluation fails.4755static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,4756QualType LVType,4757LValue &LV,4758const Expr *RHS,4759bool IncludeMember = true) {4760MemberPtr MemPtr;4761if (!EvaluateMemberPointer(RHS, MemPtr, Info))4762return nullptr;47634764// C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to4765// member value, the behavior is undefined.4766if (!MemPtr.getDecl()) {4767// FIXME: Specific diagnostic.4768Info.FFDiag(RHS);4769return nullptr;4770}47714772if (MemPtr.isDerivedMember()) {4773// This is a member of some derived class. Truncate LV appropriately.4774// The end of the derived-to-base path for the base object must match the4775// derived-to-base path for the member pointer.4776if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >4777LV.Designator.Entries.size()) {4778Info.FFDiag(RHS);4779return nullptr;4780}4781unsigned PathLengthToMember =4782LV.Designator.Entries.size() - MemPtr.Path.size();4783for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {4784const CXXRecordDecl *LVDecl = getAsBaseClass(4785LV.Designator.Entries[PathLengthToMember + I]);4786const CXXRecordDecl *MPDecl = MemPtr.Path[I];4787if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {4788Info.FFDiag(RHS);4789return nullptr;4790}4791}47924793// Truncate the lvalue to the appropriate derived class.4794if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),4795PathLengthToMember))4796return nullptr;4797} else if (!MemPtr.Path.empty()) {4798// Extend the LValue path with the member pointer's path.4799LV.Designator.Entries.reserve(LV.Designator.Entries.size() +4800MemPtr.Path.size() + IncludeMember);48014802// Walk down to the appropriate base class.4803if (const PointerType *PT = LVType->getAs<PointerType>())4804LVType = PT->getPointeeType();4805const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();4806assert(RD && "member pointer access on non-class-type expression");4807// The first class in the path is that of the lvalue.4808for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {4809const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];4810if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))4811return nullptr;4812RD = Base;4813}4814// Finally cast to the class containing the member.4815if (!HandleLValueDirectBase(Info, RHS, LV, RD,4816MemPtr.getContainingRecord()))4817return nullptr;4818}48194820// Add the member. Note that we cannot build bound member functions here.4821if (IncludeMember) {4822if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {4823if (!HandleLValueMember(Info, RHS, LV, FD))4824return nullptr;4825} else if (const IndirectFieldDecl *IFD =4826dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {4827if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))4828return nullptr;4829} else {4830llvm_unreachable("can't construct reference to bound member function");4831}4832}48334834return MemPtr.getDecl();4835}48364837static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,4838const BinaryOperator *BO,4839LValue &LV,4840bool IncludeMember = true) {4841assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);48424843if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {4844if (Info.noteFailure()) {4845MemberPtr MemPtr;4846EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);4847}4848return nullptr;4849}48504851return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,4852BO->getRHS(), IncludeMember);4853}48544855/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on4856/// the provided lvalue, which currently refers to the base object.4857static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,4858LValue &Result) {4859SubobjectDesignator &D = Result.Designator;4860if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))4861return false;48624863QualType TargetQT = E->getType();4864if (const PointerType *PT = TargetQT->getAs<PointerType>())4865TargetQT = PT->getPointeeType();48664867// Check this cast lands within the final derived-to-base subobject path.4868if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {4869Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)4870<< D.MostDerivedType << TargetQT;4871return false;4872}48734874// Check the type of the final cast. We don't need to check the path,4875// since a cast can only be formed if the path is unique.4876unsigned NewEntriesSize = D.Entries.size() - E->path_size();4877const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();4878const CXXRecordDecl *FinalType;4879if (NewEntriesSize == D.MostDerivedPathLength)4880FinalType = D.MostDerivedType->getAsCXXRecordDecl();4881else4882FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);4883if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {4884Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)4885<< D.MostDerivedType << TargetQT;4886return false;4887}48884889// Truncate the lvalue to the appropriate derived class.4890return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);4891}48924893/// Get the value to use for a default-initialized object of type T.4894/// Return false if it encounters something invalid.4895static bool handleDefaultInitValue(QualType T, APValue &Result) {4896bool Success = true;48974898// If there is already a value present don't overwrite it.4899if (!Result.isAbsent())4900return true;49014902if (auto *RD = T->getAsCXXRecordDecl()) {4903if (RD->isInvalidDecl()) {4904Result = APValue();4905return false;4906}4907if (RD->isUnion()) {4908Result = APValue((const FieldDecl *)nullptr);4909return true;4910}4911Result = APValue(APValue::UninitStruct(), RD->getNumBases(),4912std::distance(RD->field_begin(), RD->field_end()));49134914unsigned Index = 0;4915for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),4916End = RD->bases_end();4917I != End; ++I, ++Index)4918Success &=4919handleDefaultInitValue(I->getType(), Result.getStructBase(Index));49204921for (const auto *I : RD->fields()) {4922if (I->isUnnamedBitField())4923continue;4924Success &= handleDefaultInitValue(4925I->getType(), Result.getStructField(I->getFieldIndex()));4926}4927return Success;4928}49294930if (auto *AT =4931dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {4932Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());4933if (Result.hasArrayFiller())4934Success &=4935handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());49364937return Success;4938}49394940Result = APValue::IndeterminateValue();4941return true;4942}49434944namespace {4945enum EvalStmtResult {4946/// Evaluation failed.4947ESR_Failed,4948/// Hit a 'return' statement.4949ESR_Returned,4950/// Evaluation succeeded.4951ESR_Succeeded,4952/// Hit a 'continue' statement.4953ESR_Continue,4954/// Hit a 'break' statement.4955ESR_Break,4956/// Still scanning for 'case' or 'default' statement.4957ESR_CaseNotFound4958};4959}49604961static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {4962if (VD->isInvalidDecl())4963return false;4964// We don't need to evaluate the initializer for a static local.4965if (!VD->hasLocalStorage())4966return true;49674968LValue Result;4969APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),4970ScopeKind::Block, Result);49714972const Expr *InitE = VD->getInit();4973if (!InitE) {4974if (VD->getType()->isDependentType())4975return Info.noteSideEffect();4976return handleDefaultInitValue(VD->getType(), Val);4977}4978if (InitE->isValueDependent())4979return false;49804981if (!EvaluateInPlace(Val, Info, Result, InitE)) {4982// Wipe out any partially-computed value, to allow tracking that this4983// evaluation failed.4984Val = APValue();4985return false;4986}49874988return true;4989}49904991static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {4992bool OK = true;49934994if (const VarDecl *VD = dyn_cast<VarDecl>(D))4995OK &= EvaluateVarDecl(Info, VD);49964997if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))4998for (auto *BD : DD->bindings())4999if (auto *VD = BD->getHoldingVar())5000OK &= EvaluateDecl(Info, VD);50015002return OK;5003}50045005static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {5006assert(E->isValueDependent());5007if (Info.noteSideEffect())5008return true;5009assert(E->containsErrors() && "valid value-dependent expression should never "5010"reach invalid code path.");5011return false;5012}50135014/// Evaluate a condition (either a variable declaration or an expression).5015static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,5016const Expr *Cond, bool &Result) {5017if (Cond->isValueDependent())5018return false;5019FullExpressionRAII Scope(Info);5020if (CondDecl && !EvaluateDecl(Info, CondDecl))5021return false;5022if (!EvaluateAsBooleanCondition(Cond, Result, Info))5023return false;5024return Scope.destroy();5025}50265027namespace {5028/// A location where the result (returned value) of evaluating a5029/// statement should be stored.5030struct StmtResult {5031/// The APValue that should be filled in with the returned value.5032APValue &Value;5033/// The location containing the result, if any (used to support RVO).5034const LValue *Slot;5035};50365037struct TempVersionRAII {5038CallStackFrame &Frame;50395040TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {5041Frame.pushTempVersion();5042}50435044~TempVersionRAII() {5045Frame.popTempVersion();5046}5047};50485049}50505051static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,5052const Stmt *S,5053const SwitchCase *SC = nullptr);50545055/// Evaluate the body of a loop, and translate the result as appropriate.5056static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,5057const Stmt *Body,5058const SwitchCase *Case = nullptr) {5059BlockScopeRAII Scope(Info);50605061EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);5062if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())5063ESR = ESR_Failed;50645065switch (ESR) {5066case ESR_Break:5067return ESR_Succeeded;5068case ESR_Succeeded:5069case ESR_Continue:5070return ESR_Continue;5071case ESR_Failed:5072case ESR_Returned:5073case ESR_CaseNotFound:5074return ESR;5075}5076llvm_unreachable("Invalid EvalStmtResult!");5077}50785079/// Evaluate a switch statement.5080static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,5081const SwitchStmt *SS) {5082BlockScopeRAII Scope(Info);50835084// Evaluate the switch condition.5085APSInt Value;5086{5087if (const Stmt *Init = SS->getInit()) {5088EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);5089if (ESR != ESR_Succeeded) {5090if (ESR != ESR_Failed && !Scope.destroy())5091ESR = ESR_Failed;5092return ESR;5093}5094}50955096FullExpressionRAII CondScope(Info);5097if (SS->getConditionVariable() &&5098!EvaluateDecl(Info, SS->getConditionVariable()))5099return ESR_Failed;5100if (SS->getCond()->isValueDependent()) {5101// We don't know what the value is, and which branch should jump to.5102EvaluateDependentExpr(SS->getCond(), Info);5103return ESR_Failed;5104}5105if (!EvaluateInteger(SS->getCond(), Value, Info))5106return ESR_Failed;51075108if (!CondScope.destroy())5109return ESR_Failed;5110}51115112// Find the switch case corresponding to the value of the condition.5113// FIXME: Cache this lookup.5114const SwitchCase *Found = nullptr;5115for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;5116SC = SC->getNextSwitchCase()) {5117if (isa<DefaultStmt>(SC)) {5118Found = SC;5119continue;5120}51215122const CaseStmt *CS = cast<CaseStmt>(SC);5123APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);5124APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)5125: LHS;5126if (LHS <= Value && Value <= RHS) {5127Found = SC;5128break;5129}5130}51315132if (!Found)5133return Scope.destroy() ? ESR_Succeeded : ESR_Failed;51345135// Search the switch body for the switch case and evaluate it from there.5136EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);5137if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())5138return ESR_Failed;51395140switch (ESR) {5141case ESR_Break:5142return ESR_Succeeded;5143case ESR_Succeeded:5144case ESR_Continue:5145case ESR_Failed:5146case ESR_Returned:5147return ESR;5148case ESR_CaseNotFound:5149// This can only happen if the switch case is nested within a statement5150// expression. We have no intention of supporting that.5151Info.FFDiag(Found->getBeginLoc(),5152diag::note_constexpr_stmt_expr_unsupported);5153return ESR_Failed;5154}5155llvm_unreachable("Invalid EvalStmtResult!");5156}51575158static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {5159// An expression E is a core constant expression unless the evaluation of E5160// would evaluate one of the following: [C++23] - a control flow that passes5161// through a declaration of a variable with static or thread storage duration5162// unless that variable is usable in constant expressions.5163if (VD->isLocalVarDecl() && VD->isStaticLocal() &&5164!VD->isUsableInConstantExpressions(Info.Ctx)) {5165Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)5166<< (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;5167return false;5168}5169return true;5170}51715172// Evaluate a statement.5173static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,5174const Stmt *S, const SwitchCase *Case) {5175if (!Info.nextStep(S))5176return ESR_Failed;51775178// If we're hunting down a 'case' or 'default' label, recurse through5179// substatements until we hit the label.5180if (Case) {5181switch (S->getStmtClass()) {5182case Stmt::CompoundStmtClass:5183// FIXME: Precompute which substatement of a compound statement we5184// would jump to, and go straight there rather than performing a5185// linear scan each time.5186case Stmt::LabelStmtClass:5187case Stmt::AttributedStmtClass:5188case Stmt::DoStmtClass:5189break;51905191case Stmt::CaseStmtClass:5192case Stmt::DefaultStmtClass:5193if (Case == S)5194Case = nullptr;5195break;51965197case Stmt::IfStmtClass: {5198// FIXME: Precompute which side of an 'if' we would jump to, and go5199// straight there rather than scanning both sides.5200const IfStmt *IS = cast<IfStmt>(S);52015202// Wrap the evaluation in a block scope, in case it's a DeclStmt5203// preceded by our switch label.5204BlockScopeRAII Scope(Info);52055206// Step into the init statement in case it brings an (uninitialized)5207// variable into scope.5208if (const Stmt *Init = IS->getInit()) {5209EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);5210if (ESR != ESR_CaseNotFound) {5211assert(ESR != ESR_Succeeded);5212return ESR;5213}5214}52155216// Condition variable must be initialized if it exists.5217// FIXME: We can skip evaluating the body if there's a condition5218// variable, as there can't be any case labels within it.5219// (The same is true for 'for' statements.)52205221EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);5222if (ESR == ESR_Failed)5223return ESR;5224if (ESR != ESR_CaseNotFound)5225return Scope.destroy() ? ESR : ESR_Failed;5226if (!IS->getElse())5227return ESR_CaseNotFound;52285229ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);5230if (ESR == ESR_Failed)5231return ESR;5232if (ESR != ESR_CaseNotFound)5233return Scope.destroy() ? ESR : ESR_Failed;5234return ESR_CaseNotFound;5235}52365237case Stmt::WhileStmtClass: {5238EvalStmtResult ESR =5239EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);5240if (ESR != ESR_Continue)5241return ESR;5242break;5243}52445245case Stmt::ForStmtClass: {5246const ForStmt *FS = cast<ForStmt>(S);5247BlockScopeRAII Scope(Info);52485249// Step into the init statement in case it brings an (uninitialized)5250// variable into scope.5251if (const Stmt *Init = FS->getInit()) {5252EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);5253if (ESR != ESR_CaseNotFound) {5254assert(ESR != ESR_Succeeded);5255return ESR;5256}5257}52585259EvalStmtResult ESR =5260EvaluateLoopBody(Result, Info, FS->getBody(), Case);5261if (ESR != ESR_Continue)5262return ESR;5263if (const auto *Inc = FS->getInc()) {5264if (Inc->isValueDependent()) {5265if (!EvaluateDependentExpr(Inc, Info))5266return ESR_Failed;5267} else {5268FullExpressionRAII IncScope(Info);5269if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())5270return ESR_Failed;5271}5272}5273break;5274}52755276case Stmt::DeclStmtClass: {5277// Start the lifetime of any uninitialized variables we encounter. They5278// might be used by the selected branch of the switch.5279const DeclStmt *DS = cast<DeclStmt>(S);5280for (const auto *D : DS->decls()) {5281if (const auto *VD = dyn_cast<VarDecl>(D)) {5282if (!CheckLocalVariableDeclaration(Info, VD))5283return ESR_Failed;5284if (VD->hasLocalStorage() && !VD->getInit())5285if (!EvaluateVarDecl(Info, VD))5286return ESR_Failed;5287// FIXME: If the variable has initialization that can't be jumped5288// over, bail out of any immediately-surrounding compound-statement5289// too. There can't be any case labels here.5290}5291}5292return ESR_CaseNotFound;5293}52945295default:5296return ESR_CaseNotFound;5297}5298}52995300switch (S->getStmtClass()) {5301default:5302if (const Expr *E = dyn_cast<Expr>(S)) {5303if (E->isValueDependent()) {5304if (!EvaluateDependentExpr(E, Info))5305return ESR_Failed;5306} else {5307// Don't bother evaluating beyond an expression-statement which couldn't5308// be evaluated.5309// FIXME: Do we need the FullExpressionRAII object here?5310// VisitExprWithCleanups should create one when necessary.5311FullExpressionRAII Scope(Info);5312if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())5313return ESR_Failed;5314}5315return ESR_Succeeded;5316}53175318Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();5319return ESR_Failed;53205321case Stmt::NullStmtClass:5322return ESR_Succeeded;53235324case Stmt::DeclStmtClass: {5325const DeclStmt *DS = cast<DeclStmt>(S);5326for (const auto *D : DS->decls()) {5327const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);5328if (VD && !CheckLocalVariableDeclaration(Info, VD))5329return ESR_Failed;5330// Each declaration initialization is its own full-expression.5331FullExpressionRAII Scope(Info);5332if (!EvaluateDecl(Info, D) && !Info.noteFailure())5333return ESR_Failed;5334if (!Scope.destroy())5335return ESR_Failed;5336}5337return ESR_Succeeded;5338}53395340case Stmt::ReturnStmtClass: {5341const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();5342FullExpressionRAII Scope(Info);5343if (RetExpr && RetExpr->isValueDependent()) {5344EvaluateDependentExpr(RetExpr, Info);5345// We know we returned, but we don't know what the value is.5346return ESR_Failed;5347}5348if (RetExpr &&5349!(Result.Slot5350? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)5351: Evaluate(Result.Value, Info, RetExpr)))5352return ESR_Failed;5353return Scope.destroy() ? ESR_Returned : ESR_Failed;5354}53555356case Stmt::CompoundStmtClass: {5357BlockScopeRAII Scope(Info);53585359const CompoundStmt *CS = cast<CompoundStmt>(S);5360for (const auto *BI : CS->body()) {5361EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);5362if (ESR == ESR_Succeeded)5363Case = nullptr;5364else if (ESR != ESR_CaseNotFound) {5365if (ESR != ESR_Failed && !Scope.destroy())5366return ESR_Failed;5367return ESR;5368}5369}5370if (Case)5371return ESR_CaseNotFound;5372return Scope.destroy() ? ESR_Succeeded : ESR_Failed;5373}53745375case Stmt::IfStmtClass: {5376const IfStmt *IS = cast<IfStmt>(S);53775378// Evaluate the condition, as either a var decl or as an expression.5379BlockScopeRAII Scope(Info);5380if (const Stmt *Init = IS->getInit()) {5381EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);5382if (ESR != ESR_Succeeded) {5383if (ESR != ESR_Failed && !Scope.destroy())5384return ESR_Failed;5385return ESR;5386}5387}5388bool Cond;5389if (IS->isConsteval()) {5390Cond = IS->isNonNegatedConsteval();5391// If we are not in a constant context, if consteval should not evaluate5392// to true.5393if (!Info.InConstantContext)5394Cond = !Cond;5395} else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),5396Cond))5397return ESR_Failed;53985399if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {5400EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);5401if (ESR != ESR_Succeeded) {5402if (ESR != ESR_Failed && !Scope.destroy())5403return ESR_Failed;5404return ESR;5405}5406}5407return Scope.destroy() ? ESR_Succeeded : ESR_Failed;5408}54095410case Stmt::WhileStmtClass: {5411const WhileStmt *WS = cast<WhileStmt>(S);5412while (true) {5413BlockScopeRAII Scope(Info);5414bool Continue;5415if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),5416Continue))5417return ESR_Failed;5418if (!Continue)5419break;54205421EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());5422if (ESR != ESR_Continue) {5423if (ESR != ESR_Failed && !Scope.destroy())5424return ESR_Failed;5425return ESR;5426}5427if (!Scope.destroy())5428return ESR_Failed;5429}5430return ESR_Succeeded;5431}54325433case Stmt::DoStmtClass: {5434const DoStmt *DS = cast<DoStmt>(S);5435bool Continue;5436do {5437EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);5438if (ESR != ESR_Continue)5439return ESR;5440Case = nullptr;54415442if (DS->getCond()->isValueDependent()) {5443EvaluateDependentExpr(DS->getCond(), Info);5444// Bailout as we don't know whether to keep going or terminate the loop.5445return ESR_Failed;5446}5447FullExpressionRAII CondScope(Info);5448if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||5449!CondScope.destroy())5450return ESR_Failed;5451} while (Continue);5452return ESR_Succeeded;5453}54545455case Stmt::ForStmtClass: {5456const ForStmt *FS = cast<ForStmt>(S);5457BlockScopeRAII ForScope(Info);5458if (FS->getInit()) {5459EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());5460if (ESR != ESR_Succeeded) {5461if (ESR != ESR_Failed && !ForScope.destroy())5462return ESR_Failed;5463return ESR;5464}5465}5466while (true) {5467BlockScopeRAII IterScope(Info);5468bool Continue = true;5469if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),5470FS->getCond(), Continue))5471return ESR_Failed;5472if (!Continue)5473break;54745475EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());5476if (ESR != ESR_Continue) {5477if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))5478return ESR_Failed;5479return ESR;5480}54815482if (const auto *Inc = FS->getInc()) {5483if (Inc->isValueDependent()) {5484if (!EvaluateDependentExpr(Inc, Info))5485return ESR_Failed;5486} else {5487FullExpressionRAII IncScope(Info);5488if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())5489return ESR_Failed;5490}5491}54925493if (!IterScope.destroy())5494return ESR_Failed;5495}5496return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;5497}54985499case Stmt::CXXForRangeStmtClass: {5500const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);5501BlockScopeRAII Scope(Info);55025503// Evaluate the init-statement if present.5504if (FS->getInit()) {5505EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());5506if (ESR != ESR_Succeeded) {5507if (ESR != ESR_Failed && !Scope.destroy())5508return ESR_Failed;5509return ESR;5510}5511}55125513// Initialize the __range variable.5514EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());5515if (ESR != ESR_Succeeded) {5516if (ESR != ESR_Failed && !Scope.destroy())5517return ESR_Failed;5518return ESR;5519}55205521// In error-recovery cases it's possible to get here even if we failed to5522// synthesize the __begin and __end variables.5523if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())5524return ESR_Failed;55255526// Create the __begin and __end iterators.5527ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());5528if (ESR != ESR_Succeeded) {5529if (ESR != ESR_Failed && !Scope.destroy())5530return ESR_Failed;5531return ESR;5532}5533ESR = EvaluateStmt(Result, Info, FS->getEndStmt());5534if (ESR != ESR_Succeeded) {5535if (ESR != ESR_Failed && !Scope.destroy())5536return ESR_Failed;5537return ESR;5538}55395540while (true) {5541// Condition: __begin != __end.5542{5543if (FS->getCond()->isValueDependent()) {5544EvaluateDependentExpr(FS->getCond(), Info);5545// We don't know whether to keep going or terminate the loop.5546return ESR_Failed;5547}5548bool Continue = true;5549FullExpressionRAII CondExpr(Info);5550if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))5551return ESR_Failed;5552if (!Continue)5553break;5554}55555556// User's variable declaration, initialized by *__begin.5557BlockScopeRAII InnerScope(Info);5558ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());5559if (ESR != ESR_Succeeded) {5560if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))5561return ESR_Failed;5562return ESR;5563}55645565// Loop body.5566ESR = EvaluateLoopBody(Result, Info, FS->getBody());5567if (ESR != ESR_Continue) {5568if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))5569return ESR_Failed;5570return ESR;5571}5572if (FS->getInc()->isValueDependent()) {5573if (!EvaluateDependentExpr(FS->getInc(), Info))5574return ESR_Failed;5575} else {5576// Increment: ++__begin5577if (!EvaluateIgnoredValue(Info, FS->getInc()))5578return ESR_Failed;5579}55805581if (!InnerScope.destroy())5582return ESR_Failed;5583}55845585return Scope.destroy() ? ESR_Succeeded : ESR_Failed;5586}55875588case Stmt::SwitchStmtClass:5589return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));55905591case Stmt::ContinueStmtClass:5592return ESR_Continue;55935594case Stmt::BreakStmtClass:5595return ESR_Break;55965597case Stmt::LabelStmtClass:5598return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);55995600case Stmt::AttributedStmtClass: {5601const auto *AS = cast<AttributedStmt>(S);5602const auto *SS = AS->getSubStmt();5603MSConstexprContextRAII ConstexprContext(5604*Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&5605isa<ReturnStmt>(SS));56065607auto LO = Info.getCtx().getLangOpts();5608if (LO.CXXAssumptions && !LO.MSVCCompat) {5609for (auto *Attr : AS->getAttrs()) {5610auto *AA = dyn_cast<CXXAssumeAttr>(Attr);5611if (!AA)5612continue;56135614auto *Assumption = AA->getAssumption();5615if (Assumption->isValueDependent())5616return ESR_Failed;56175618if (Assumption->HasSideEffects(Info.getCtx()))5619continue;56205621bool Value;5622if (!EvaluateAsBooleanCondition(Assumption, Value, Info))5623return ESR_Failed;5624if (!Value) {5625Info.CCEDiag(Assumption->getExprLoc(),5626diag::note_constexpr_assumption_failed);5627return ESR_Failed;5628}5629}5630}56315632return EvaluateStmt(Result, Info, SS, Case);5633}56345635case Stmt::CaseStmtClass:5636case Stmt::DefaultStmtClass:5637return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);5638case Stmt::CXXTryStmtClass:5639// Evaluate try blocks by evaluating all sub statements.5640return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);5641}5642}56435644/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial5645/// default constructor. If so, we'll fold it whether or not it's marked as5646/// constexpr. If it is marked as constexpr, we will never implicitly define it,5647/// so we need special handling.5648static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,5649const CXXConstructorDecl *CD,5650bool IsValueInitialization) {5651if (!CD->isTrivial() || !CD->isDefaultConstructor())5652return false;56535654// Value-initialization does not call a trivial default constructor, so such a5655// call is a core constant expression whether or not the constructor is5656// constexpr.5657if (!CD->isConstexpr() && !IsValueInitialization) {5658if (Info.getLangOpts().CPlusPlus11) {5659// FIXME: If DiagDecl is an implicitly-declared special member function,5660// we should be much more explicit about why it's not constexpr.5661Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)5662<< /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;5663Info.Note(CD->getLocation(), diag::note_declared_at);5664} else {5665Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);5666}5667}5668return true;5669}56705671/// CheckConstexprFunction - Check that a function can be called in a constant5672/// expression.5673static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,5674const FunctionDecl *Declaration,5675const FunctionDecl *Definition,5676const Stmt *Body) {5677// Potential constant expressions can contain calls to declared, but not yet5678// defined, constexpr functions.5679if (Info.checkingPotentialConstantExpression() && !Definition &&5680Declaration->isConstexpr())5681return false;56825683// Bail out if the function declaration itself is invalid. We will5684// have produced a relevant diagnostic while parsing it, so just5685// note the problematic sub-expression.5686if (Declaration->isInvalidDecl()) {5687Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);5688return false;5689}56905691// DR1872: An instantiated virtual constexpr function can't be called in a5692// constant expression (prior to C++20). We can still constant-fold such a5693// call.5694if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&5695cast<CXXMethodDecl>(Declaration)->isVirtual())5696Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);56975698if (Definition && Definition->isInvalidDecl()) {5699Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);5700return false;5701}57025703// Can we evaluate this function call?5704if (Definition && Body &&5705(Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&5706Definition->hasAttr<MSConstexprAttr>())))5707return true;57085709if (Info.getLangOpts().CPlusPlus11) {5710const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;57115712// If this function is not constexpr because it is an inherited5713// non-constexpr constructor, diagnose that directly.5714auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);5715if (CD && CD->isInheritingConstructor()) {5716auto *Inherited = CD->getInheritedConstructor().getConstructor();5717if (!Inherited->isConstexpr())5718DiagDecl = CD = Inherited;5719}57205721// FIXME: If DiagDecl is an implicitly-declared special member function5722// or an inheriting constructor, we should be much more explicit about why5723// it's not constexpr.5724if (CD && CD->isInheritingConstructor())5725Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)5726<< CD->getInheritedConstructor().getConstructor()->getParent();5727else5728Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)5729<< DiagDecl->isConstexpr() << (bool)CD << DiagDecl;5730Info.Note(DiagDecl->getLocation(), diag::note_declared_at);5731} else {5732Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);5733}5734return false;5735}57365737namespace {5738struct CheckDynamicTypeHandler {5739AccessKinds AccessKind;5740typedef bool result_type;5741bool failed() { return false; }5742bool found(APValue &Subobj, QualType SubobjType) { return true; }5743bool found(APSInt &Value, QualType SubobjType) { return true; }5744bool found(APFloat &Value, QualType SubobjType) { return true; }5745};5746} // end anonymous namespace57475748/// Check that we can access the notional vptr of an object / determine its5749/// dynamic type.5750static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,5751AccessKinds AK, bool Polymorphic) {5752if (This.Designator.Invalid)5753return false;57545755CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());57565757if (!Obj)5758return false;57595760if (!Obj.Value) {5761// The object is not usable in constant expressions, so we can't inspect5762// its value to see if it's in-lifetime or what the active union members5763// are. We can still check for a one-past-the-end lvalue.5764if (This.Designator.isOnePastTheEnd() ||5765This.Designator.isMostDerivedAnUnsizedArray()) {5766Info.FFDiag(E, This.Designator.isOnePastTheEnd()5767? diag::note_constexpr_access_past_end5768: diag::note_constexpr_access_unsized_array)5769<< AK;5770return false;5771} else if (Polymorphic) {5772// Conservatively refuse to perform a polymorphic operation if we would5773// not be able to read a notional 'vptr' value.5774APValue Val;5775This.moveInto(Val);5776QualType StarThisType =5777Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));5778Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)5779<< AK << Val.getAsString(Info.Ctx, StarThisType);5780return false;5781}5782return true;5783}57845785CheckDynamicTypeHandler Handler{AK};5786return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);5787}57885789/// Check that the pointee of the 'this' pointer in a member function call is5790/// either within its lifetime or in its period of construction or destruction.5791static bool5792checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,5793const LValue &This,5794const CXXMethodDecl *NamedMember) {5795return checkDynamicType(5796Info, E, This,5797isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);5798}57995800struct DynamicType {5801/// The dynamic class type of the object.5802const CXXRecordDecl *Type;5803/// The corresponding path length in the lvalue.5804unsigned PathLength;5805};58065807static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,5808unsigned PathLength) {5809assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=5810Designator.Entries.size() && "invalid path length");5811return (PathLength == Designator.MostDerivedPathLength)5812? Designator.MostDerivedType->getAsCXXRecordDecl()5813: getAsBaseClass(Designator.Entries[PathLength - 1]);5814}58155816/// Determine the dynamic type of an object.5817static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,5818const Expr *E,5819LValue &This,5820AccessKinds AK) {5821// If we don't have an lvalue denoting an object of class type, there is no5822// meaningful dynamic type. (We consider objects of non-class type to have no5823// dynamic type.)5824if (!checkDynamicType(Info, E, This, AK, true))5825return std::nullopt;58265827// Refuse to compute a dynamic type in the presence of virtual bases. This5828// shouldn't happen other than in constant-folding situations, since literal5829// types can't have virtual bases.5830//5831// Note that consumers of DynamicType assume that the type has no virtual5832// bases, and will need modifications if this restriction is relaxed.5833const CXXRecordDecl *Class =5834This.Designator.MostDerivedType->getAsCXXRecordDecl();5835if (!Class || Class->getNumVBases()) {5836Info.FFDiag(E);5837return std::nullopt;5838}58395840// FIXME: For very deep class hierarchies, it might be beneficial to use a5841// binary search here instead. But the overwhelmingly common case is that5842// we're not in the middle of a constructor, so it probably doesn't matter5843// in practice.5844ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;5845for (unsigned PathLength = This.Designator.MostDerivedPathLength;5846PathLength <= Path.size(); ++PathLength) {5847switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),5848Path.slice(0, PathLength))) {5849case ConstructionPhase::Bases:5850case ConstructionPhase::DestroyingBases:5851// We're constructing or destroying a base class. This is not the dynamic5852// type.5853break;58545855case ConstructionPhase::None:5856case ConstructionPhase::AfterBases:5857case ConstructionPhase::AfterFields:5858case ConstructionPhase::Destroying:5859// We've finished constructing the base classes and not yet started5860// destroying them again, so this is the dynamic type.5861return DynamicType{getBaseClassType(This.Designator, PathLength),5862PathLength};5863}5864}58655866// CWG issue 1517: we're constructing a base class of the object described by5867// 'This', so that object has not yet begun its period of construction and5868// any polymorphic operation on it results in undefined behavior.5869Info.FFDiag(E);5870return std::nullopt;5871}58725873/// Perform virtual dispatch.5874static const CXXMethodDecl *HandleVirtualDispatch(5875EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,5876llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {5877std::optional<DynamicType> DynType = ComputeDynamicType(5878Info, E, This,5879isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);5880if (!DynType)5881return nullptr;58825883// Find the final overrider. It must be declared in one of the classes on the5884// path from the dynamic type to the static type.5885// FIXME: If we ever allow literal types to have virtual base classes, that5886// won't be true.5887const CXXMethodDecl *Callee = Found;5888unsigned PathLength = DynType->PathLength;5889for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {5890const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);5891const CXXMethodDecl *Overrider =5892Found->getCorrespondingMethodDeclaredInClass(Class, false);5893if (Overrider) {5894Callee = Overrider;5895break;5896}5897}58985899// C++2a [class.abstract]p6:5900// the effect of making a virtual call to a pure virtual function [...] is5901// undefined5902if (Callee->isPureVirtual()) {5903Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;5904Info.Note(Callee->getLocation(), diag::note_declared_at);5905return nullptr;5906}59075908// If necessary, walk the rest of the path to determine the sequence of5909// covariant adjustment steps to apply.5910if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),5911Found->getReturnType())) {5912CovariantAdjustmentPath.push_back(Callee->getReturnType());5913for (unsigned CovariantPathLength = PathLength + 1;5914CovariantPathLength != This.Designator.Entries.size();5915++CovariantPathLength) {5916const CXXRecordDecl *NextClass =5917getBaseClassType(This.Designator, CovariantPathLength);5918const CXXMethodDecl *Next =5919Found->getCorrespondingMethodDeclaredInClass(NextClass, false);5920if (Next && !Info.Ctx.hasSameUnqualifiedType(5921Next->getReturnType(), CovariantAdjustmentPath.back()))5922CovariantAdjustmentPath.push_back(Next->getReturnType());5923}5924if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),5925CovariantAdjustmentPath.back()))5926CovariantAdjustmentPath.push_back(Found->getReturnType());5927}59285929// Perform 'this' adjustment.5930if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))5931return nullptr;59325933return Callee;5934}59355936/// Perform the adjustment from a value returned by a virtual function to5937/// a value of the statically expected type, which may be a pointer or5938/// reference to a base class of the returned type.5939static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,5940APValue &Result,5941ArrayRef<QualType> Path) {5942assert(Result.isLValue() &&5943"unexpected kind of APValue for covariant return");5944if (Result.isNullPointer())5945return true;59465947LValue LVal;5948LVal.setFrom(Info.Ctx, Result);59495950const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();5951for (unsigned I = 1; I != Path.size(); ++I) {5952const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();5953assert(OldClass && NewClass && "unexpected kind of covariant return");5954if (OldClass != NewClass &&5955!CastToBaseClass(Info, E, LVal, OldClass, NewClass))5956return false;5957OldClass = NewClass;5958}59595960LVal.moveInto(Result);5961return true;5962}59635964/// Determine whether \p Base, which is known to be a direct base class of5965/// \p Derived, is a public base class.5966static bool isBaseClassPublic(const CXXRecordDecl *Derived,5967const CXXRecordDecl *Base) {5968for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {5969auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();5970if (BaseClass && declaresSameEntity(BaseClass, Base))5971return BaseSpec.getAccessSpecifier() == AS_public;5972}5973llvm_unreachable("Base is not a direct base of Derived");5974}59755976/// Apply the given dynamic cast operation on the provided lvalue.5977///5978/// This implements the hard case of dynamic_cast, requiring a "runtime check"5979/// to find a suitable target subobject.5980static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,5981LValue &Ptr) {5982// We can't do anything with a non-symbolic pointer value.5983SubobjectDesignator &D = Ptr.Designator;5984if (D.Invalid)5985return false;59865987// C++ [expr.dynamic.cast]p6:5988// If v is a null pointer value, the result is a null pointer value.5989if (Ptr.isNullPointer() && !E->isGLValue())5990return true;59915992// For all the other cases, we need the pointer to point to an object within5993// its lifetime / period of construction / destruction, and we need to know5994// its dynamic type.5995std::optional<DynamicType> DynType =5996ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);5997if (!DynType)5998return false;59996000// C++ [expr.dynamic.cast]p7:6001// If T is "pointer to cv void", then the result is a pointer to the most6002// derived object6003if (E->getType()->isVoidPointerType())6004return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);60056006const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();6007assert(C && "dynamic_cast target is not void pointer nor class");6008CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));60096010auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {6011// C++ [expr.dynamic.cast]p9:6012if (!E->isGLValue()) {6013// The value of a failed cast to pointer type is the null pointer value6014// of the required result type.6015Ptr.setNull(Info.Ctx, E->getType());6016return true;6017}60186019// A failed cast to reference type throws [...] std::bad_cast.6020unsigned DiagKind;6021if (!Paths && (declaresSameEntity(DynType->Type, C) ||6022DynType->Type->isDerivedFrom(C)))6023DiagKind = 0;6024else if (!Paths || Paths->begin() == Paths->end())6025DiagKind = 1;6026else if (Paths->isAmbiguous(CQT))6027DiagKind = 2;6028else {6029assert(Paths->front().Access != AS_public && "why did the cast fail?");6030DiagKind = 3;6031}6032Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)6033<< DiagKind << Ptr.Designator.getType(Info.Ctx)6034<< Info.Ctx.getRecordType(DynType->Type)6035<< E->getType().getUnqualifiedType();6036return false;6037};60386039// Runtime check, phase 1:6040// Walk from the base subobject towards the derived object looking for the6041// target type.6042for (int PathLength = Ptr.Designator.Entries.size();6043PathLength >= (int)DynType->PathLength; --PathLength) {6044const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);6045if (declaresSameEntity(Class, C))6046return CastToDerivedClass(Info, E, Ptr, Class, PathLength);6047// We can only walk across public inheritance edges.6048if (PathLength > (int)DynType->PathLength &&6049!isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),6050Class))6051return RuntimeCheckFailed(nullptr);6052}60536054// Runtime check, phase 2:6055// Search the dynamic type for an unambiguous public base of type C.6056CXXBasePaths Paths(/*FindAmbiguities=*/true,6057/*RecordPaths=*/true, /*DetectVirtual=*/false);6058if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&6059Paths.front().Access == AS_public) {6060// Downcast to the dynamic type...6061if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))6062return false;6063// ... then upcast to the chosen base class subobject.6064for (CXXBasePathElement &Elem : Paths.front())6065if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))6066return false;6067return true;6068}60696070// Otherwise, the runtime check fails.6071return RuntimeCheckFailed(&Paths);6072}60736074namespace {6075struct StartLifetimeOfUnionMemberHandler {6076EvalInfo &Info;6077const Expr *LHSExpr;6078const FieldDecl *Field;6079bool DuringInit;6080bool Failed = false;6081static const AccessKinds AccessKind = AK_Assign;60826083typedef bool result_type;6084bool failed() { return Failed; }6085bool found(APValue &Subobj, QualType SubobjType) {6086// We are supposed to perform no initialization but begin the lifetime of6087// the object. We interpret that as meaning to do what default6088// initialization of the object would do if all constructors involved were6089// trivial:6090// * All base, non-variant member, and array element subobjects' lifetimes6091// begin6092// * No variant members' lifetimes begin6093// * All scalar subobjects whose lifetimes begin have indeterminate values6094assert(SubobjType->isUnionType());6095if (declaresSameEntity(Subobj.getUnionField(), Field)) {6096// This union member is already active. If it's also in-lifetime, there's6097// nothing to do.6098if (Subobj.getUnionValue().hasValue())6099return true;6100} else if (DuringInit) {6101// We're currently in the process of initializing a different union6102// member. If we carried on, that initialization would attempt to6103// store to an inactive union member, resulting in undefined behavior.6104Info.FFDiag(LHSExpr,6105diag::note_constexpr_union_member_change_during_init);6106return false;6107}6108APValue Result;6109Failed = !handleDefaultInitValue(Field->getType(), Result);6110Subobj.setUnion(Field, Result);6111return true;6112}6113bool found(APSInt &Value, QualType SubobjType) {6114llvm_unreachable("wrong value kind for union object");6115}6116bool found(APFloat &Value, QualType SubobjType) {6117llvm_unreachable("wrong value kind for union object");6118}6119};6120} // end anonymous namespace61216122const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;61236124/// Handle a builtin simple-assignment or a call to a trivial assignment6125/// operator whose left-hand side might involve a union member access. If it6126/// does, implicitly start the lifetime of any accessed union elements per6127/// C++20 [class.union]5.6128static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,6129const Expr *LHSExpr,6130const LValue &LHS) {6131if (LHS.InvalidBase || LHS.Designator.Invalid)6132return false;61336134llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;6135// C++ [class.union]p5:6136// define the set S(E) of subexpressions of E as follows:6137unsigned PathLength = LHS.Designator.Entries.size();6138for (const Expr *E = LHSExpr; E != nullptr;) {6139// -- If E is of the form A.B, S(E) contains the elements of S(A)...6140if (auto *ME = dyn_cast<MemberExpr>(E)) {6141auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());6142// Note that we can't implicitly start the lifetime of a reference,6143// so we don't need to proceed any further if we reach one.6144if (!FD || FD->getType()->isReferenceType())6145break;61466147// ... and also contains A.B if B names a union member ...6148if (FD->getParent()->isUnion()) {6149// ... of a non-class, non-array type, or of a class type with a6150// trivial default constructor that is not deleted, or an array of6151// such types.6152auto *RD =6153FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();6154if (!RD || RD->hasTrivialDefaultConstructor())6155UnionPathLengths.push_back({PathLength - 1, FD});6156}61576158E = ME->getBase();6159--PathLength;6160assert(declaresSameEntity(FD,6161LHS.Designator.Entries[PathLength]6162.getAsBaseOrMember().getPointer()));61636164// -- If E is of the form A[B] and is interpreted as a built-in array6165// subscripting operator, S(E) is [S(the array operand, if any)].6166} else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {6167// Step over an ArrayToPointerDecay implicit cast.6168auto *Base = ASE->getBase()->IgnoreImplicit();6169if (!Base->getType()->isArrayType())6170break;61716172E = Base;6173--PathLength;61746175} else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {6176// Step over a derived-to-base conversion.6177E = ICE->getSubExpr();6178if (ICE->getCastKind() == CK_NoOp)6179continue;6180if (ICE->getCastKind() != CK_DerivedToBase &&6181ICE->getCastKind() != CK_UncheckedDerivedToBase)6182break;6183// Walk path backwards as we walk up from the base to the derived class.6184for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {6185if (Elt->isVirtual()) {6186// A class with virtual base classes never has a trivial default6187// constructor, so S(E) is empty in this case.6188E = nullptr;6189break;6190}61916192--PathLength;6193assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),6194LHS.Designator.Entries[PathLength]6195.getAsBaseOrMember().getPointer()));6196}61976198// -- Otherwise, S(E) is empty.6199} else {6200break;6201}6202}62036204// Common case: no unions' lifetimes are started.6205if (UnionPathLengths.empty())6206return true;62076208// if modification of X [would access an inactive union member], an object6209// of the type of X is implicitly created6210CompleteObject Obj =6211findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());6212if (!Obj)6213return false;6214for (std::pair<unsigned, const FieldDecl *> LengthAndField :6215llvm::reverse(UnionPathLengths)) {6216// Form a designator for the union object.6217SubobjectDesignator D = LHS.Designator;6218D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);62196220bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==6221ConstructionPhase::AfterBases;6222StartLifetimeOfUnionMemberHandler StartLifetime{6223Info, LHSExpr, LengthAndField.second, DuringInit};6224if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))6225return false;6226}62276228return true;6229}62306231static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,6232CallRef Call, EvalInfo &Info,6233bool NonNull = false) {6234LValue LV;6235// Create the parameter slot and register its destruction. For a vararg6236// argument, create a temporary.6237// FIXME: For calling conventions that destroy parameters in the callee,6238// should we consider performing destruction when the function returns6239// instead?6240APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)6241: Info.CurrentCall->createTemporary(Arg, Arg->getType(),6242ScopeKind::Call, LV);6243if (!EvaluateInPlace(V, Info, LV, Arg))6244return false;62456246// Passing a null pointer to an __attribute__((nonnull)) parameter results in6247// undefined behavior, so is non-constant.6248if (NonNull && V.isLValue() && V.isNullPointer()) {6249Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);6250return false;6251}62526253return true;6254}62556256/// Evaluate the arguments to a function call.6257static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,6258EvalInfo &Info, const FunctionDecl *Callee,6259bool RightToLeft = false) {6260bool Success = true;6261llvm::SmallBitVector ForbiddenNullArgs;6262if (Callee->hasAttr<NonNullAttr>()) {6263ForbiddenNullArgs.resize(Args.size());6264for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {6265if (!Attr->args_size()) {6266ForbiddenNullArgs.set();6267break;6268} else6269for (auto Idx : Attr->args()) {6270unsigned ASTIdx = Idx.getASTIndex();6271if (ASTIdx >= Args.size())6272continue;6273ForbiddenNullArgs[ASTIdx] = true;6274}6275}6276}6277for (unsigned I = 0; I < Args.size(); I++) {6278unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;6279const ParmVarDecl *PVD =6280Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;6281bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];6282if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {6283// If we're checking for a potential constant expression, evaluate all6284// initializers even if some of them fail.6285if (!Info.noteFailure())6286return false;6287Success = false;6288}6289}6290return Success;6291}62926293/// Perform a trivial copy from Param, which is the parameter of a copy or move6294/// constructor or assignment operator.6295static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,6296const Expr *E, APValue &Result,6297bool CopyObjectRepresentation) {6298// Find the reference argument.6299CallStackFrame *Frame = Info.CurrentCall;6300APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);6301if (!RefValue) {6302Info.FFDiag(E);6303return false;6304}63056306// Copy out the contents of the RHS object.6307LValue RefLValue;6308RefLValue.setFrom(Info.Ctx, *RefValue);6309return handleLValueToRValueConversion(6310Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,6311CopyObjectRepresentation);6312}63136314/// Evaluate a function call.6315static bool HandleFunctionCall(SourceLocation CallLoc,6316const FunctionDecl *Callee, const LValue *This,6317const Expr *E, ArrayRef<const Expr *> Args,6318CallRef Call, const Stmt *Body, EvalInfo &Info,6319APValue &Result, const LValue *ResultSlot) {6320if (!Info.CheckCallLimit(CallLoc))6321return false;63226323CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);63246325// For a trivial copy or move assignment, perform an APValue copy. This is6326// essential for unions, where the operations performed by the assignment6327// operator cannot be represented as statements.6328//6329// Skip this for non-union classes with no fields; in that case, the defaulted6330// copy/move does not actually read the object.6331const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);6332if (MD && MD->isDefaulted() &&6333(MD->getParent()->isUnion() ||6334(MD->isTrivial() &&6335isReadByLvalueToRvalueConversion(MD->getParent())))) {6336assert(This &&6337(MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));6338APValue RHSValue;6339if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,6340MD->getParent()->isUnion()))6341return false;6342if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),6343RHSValue))6344return false;6345This->moveInto(Result);6346return true;6347} else if (MD && isLambdaCallOperator(MD)) {6348// We're in a lambda; determine the lambda capture field maps unless we're6349// just constexpr checking a lambda's call operator. constexpr checking is6350// done before the captures have been added to the closure object (unless6351// we're inferring constexpr-ness), so we don't have access to them in this6352// case. But since we don't need the captures to constexpr check, we can6353// just ignore them.6354if (!Info.checkingPotentialConstantExpression())6355MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,6356Frame.LambdaThisCaptureField);6357}63586359StmtResult Ret = {Result, ResultSlot};6360EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);6361if (ESR == ESR_Succeeded) {6362if (Callee->getReturnType()->isVoidType())6363return true;6364Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);6365}6366return ESR == ESR_Returned;6367}63686369/// Evaluate a constructor call.6370static bool HandleConstructorCall(const Expr *E, const LValue &This,6371CallRef Call,6372const CXXConstructorDecl *Definition,6373EvalInfo &Info, APValue &Result) {6374SourceLocation CallLoc = E->getExprLoc();6375if (!Info.CheckCallLimit(CallLoc))6376return false;63776378const CXXRecordDecl *RD = Definition->getParent();6379if (RD->getNumVBases()) {6380Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;6381return false;6382}63836384EvalInfo::EvaluatingConstructorRAII EvalObj(6385Info,6386ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},6387RD->getNumBases());6388CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);63896390// FIXME: Creating an APValue just to hold a nonexistent return value is6391// wasteful.6392APValue RetVal;6393StmtResult Ret = {RetVal, nullptr};63946395// If it's a delegating constructor, delegate.6396if (Definition->isDelegatingConstructor()) {6397CXXConstructorDecl::init_const_iterator I = Definition->init_begin();6398if ((*I)->getInit()->isValueDependent()) {6399if (!EvaluateDependentExpr((*I)->getInit(), Info))6400return false;6401} else {6402FullExpressionRAII InitScope(Info);6403if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||6404!InitScope.destroy())6405return false;6406}6407return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;6408}64096410// For a trivial copy or move constructor, perform an APValue copy. This is6411// essential for unions (or classes with anonymous union members), where the6412// operations performed by the constructor cannot be represented by6413// ctor-initializers.6414//6415// Skip this for empty non-union classes; we should not perform an6416// lvalue-to-rvalue conversion on them because their copy constructor does not6417// actually read them.6418if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&6419(Definition->getParent()->isUnion() ||6420(Definition->isTrivial() &&6421isReadByLvalueToRvalueConversion(Definition->getParent())))) {6422return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,6423Definition->getParent()->isUnion());6424}64256426// Reserve space for the struct members.6427if (!Result.hasValue()) {6428if (!RD->isUnion())6429Result = APValue(APValue::UninitStruct(), RD->getNumBases(),6430std::distance(RD->field_begin(), RD->field_end()));6431else6432// A union starts with no active member.6433Result = APValue((const FieldDecl*)nullptr);6434}64356436if (RD->isInvalidDecl()) return false;6437const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);64386439// A scope for temporaries lifetime-extended by reference members.6440BlockScopeRAII LifetimeExtendedScope(Info);64416442bool Success = true;6443unsigned BasesSeen = 0;6444#ifndef NDEBUG6445CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();6446#endif6447CXXRecordDecl::field_iterator FieldIt = RD->field_begin();6448auto SkipToField = [&](FieldDecl *FD, bool Indirect) {6449// We might be initializing the same field again if this is an indirect6450// field initialization.6451if (FieldIt == RD->field_end() ||6452FieldIt->getFieldIndex() > FD->getFieldIndex()) {6453assert(Indirect && "fields out of order?");6454return;6455}64566457// Default-initialize any fields with no explicit initializer.6458for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {6459assert(FieldIt != RD->field_end() && "missing field?");6460if (!FieldIt->isUnnamedBitField())6461Success &= handleDefaultInitValue(6462FieldIt->getType(),6463Result.getStructField(FieldIt->getFieldIndex()));6464}6465++FieldIt;6466};6467for (const auto *I : Definition->inits()) {6468LValue Subobject = This;6469LValue SubobjectParent = This;6470APValue *Value = &Result;64716472// Determine the subobject to initialize.6473FieldDecl *FD = nullptr;6474if (I->isBaseInitializer()) {6475QualType BaseType(I->getBaseClass(), 0);6476#ifndef NDEBUG6477// Non-virtual base classes are initialized in the order in the class6478// definition. We have already checked for virtual base classes.6479assert(!BaseIt->isVirtual() && "virtual base for literal type");6480assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&6481"base class initializers not in expected order");6482++BaseIt;6483#endif6484if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,6485BaseType->getAsCXXRecordDecl(), &Layout))6486return false;6487Value = &Result.getStructBase(BasesSeen++);6488} else if ((FD = I->getMember())) {6489if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))6490return false;6491if (RD->isUnion()) {6492Result = APValue(FD);6493Value = &Result.getUnionValue();6494} else {6495SkipToField(FD, false);6496Value = &Result.getStructField(FD->getFieldIndex());6497}6498} else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {6499// Walk the indirect field decl's chain to find the object to initialize,6500// and make sure we've initialized every step along it.6501auto IndirectFieldChain = IFD->chain();6502for (auto *C : IndirectFieldChain) {6503FD = cast<FieldDecl>(C);6504CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());6505// Switch the union field if it differs. This happens if we had6506// preceding zero-initialization, and we're now initializing a union6507// subobject other than the first.6508// FIXME: In this case, the values of the other subobjects are6509// specified, since zero-initialization sets all padding bits to zero.6510if (!Value->hasValue() ||6511(Value->isUnion() && Value->getUnionField() != FD)) {6512if (CD->isUnion())6513*Value = APValue(FD);6514else6515// FIXME: This immediately starts the lifetime of all members of6516// an anonymous struct. It would be preferable to strictly start6517// member lifetime in initialization order.6518Success &=6519handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);6520}6521// Store Subobject as its parent before updating it for the last element6522// in the chain.6523if (C == IndirectFieldChain.back())6524SubobjectParent = Subobject;6525if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))6526return false;6527if (CD->isUnion())6528Value = &Value->getUnionValue();6529else {6530if (C == IndirectFieldChain.front() && !RD->isUnion())6531SkipToField(FD, true);6532Value = &Value->getStructField(FD->getFieldIndex());6533}6534}6535} else {6536llvm_unreachable("unknown base initializer kind");6537}65386539// Need to override This for implicit field initializers as in this case6540// This refers to innermost anonymous struct/union containing initializer,6541// not to currently constructed class.6542const Expr *Init = I->getInit();6543if (Init->isValueDependent()) {6544if (!EvaluateDependentExpr(Init, Info))6545return false;6546} else {6547ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,6548isa<CXXDefaultInitExpr>(Init));6549FullExpressionRAII InitScope(Info);6550if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||6551(FD && FD->isBitField() &&6552!truncateBitfieldValue(Info, Init, *Value, FD))) {6553// If we're checking for a potential constant expression, evaluate all6554// initializers even if some of them fail.6555if (!Info.noteFailure())6556return false;6557Success = false;6558}6559}65606561// This is the point at which the dynamic type of the object becomes this6562// class type.6563if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())6564EvalObj.finishedConstructingBases();6565}65666567// Default-initialize any remaining fields.6568if (!RD->isUnion()) {6569for (; FieldIt != RD->field_end(); ++FieldIt) {6570if (!FieldIt->isUnnamedBitField())6571Success &= handleDefaultInitValue(6572FieldIt->getType(),6573Result.getStructField(FieldIt->getFieldIndex()));6574}6575}65766577EvalObj.finishedConstructingFields();65786579return Success &&6580EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&6581LifetimeExtendedScope.destroy();6582}65836584static bool HandleConstructorCall(const Expr *E, const LValue &This,6585ArrayRef<const Expr*> Args,6586const CXXConstructorDecl *Definition,6587EvalInfo &Info, APValue &Result) {6588CallScopeRAII CallScope(Info);6589CallRef Call = Info.CurrentCall->createCall(Definition);6590if (!EvaluateArgs(Args, Call, Info, Definition))6591return false;65926593return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&6594CallScope.destroy();6595}65966597static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,6598const LValue &This, APValue &Value,6599QualType T) {6600// Objects can only be destroyed while they're within their lifetimes.6601// FIXME: We have no representation for whether an object of type nullptr_t6602// is in its lifetime; it usually doesn't matter. Perhaps we should model it6603// as indeterminate instead?6604if (Value.isAbsent() && !T->isNullPtrType()) {6605APValue Printable;6606This.moveInto(Printable);6607Info.FFDiag(CallRange.getBegin(),6608diag::note_constexpr_destroy_out_of_lifetime)6609<< Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));6610return false;6611}66126613// Invent an expression for location purposes.6614// FIXME: We shouldn't need to do this.6615OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);66166617// For arrays, destroy elements right-to-left.6618if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {6619uint64_t Size = CAT->getZExtSize();6620QualType ElemT = CAT->getElementType();66216622if (!CheckArraySize(Info, CAT, CallRange.getBegin()))6623return false;66246625LValue ElemLV = This;6626ElemLV.addArray(Info, &LocE, CAT);6627if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))6628return false;66296630// Ensure that we have actual array elements available to destroy; the6631// destructors might mutate the value, so we can't run them on the array6632// filler.6633if (Size && Size > Value.getArrayInitializedElts())6634expandArray(Value, Value.getArraySize() - 1);66356636for (; Size != 0; --Size) {6637APValue &Elem = Value.getArrayInitializedElt(Size - 1);6638if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||6639!HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))6640return false;6641}66426643// End the lifetime of this array now.6644Value = APValue();6645return true;6646}66476648const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6649if (!RD) {6650if (T.isDestructedType()) {6651Info.FFDiag(CallRange.getBegin(),6652diag::note_constexpr_unsupported_destruction)6653<< T;6654return false;6655}66566657Value = APValue();6658return true;6659}66606661if (RD->getNumVBases()) {6662Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;6663return false;6664}66656666const CXXDestructorDecl *DD = RD->getDestructor();6667if (!DD && !RD->hasTrivialDestructor()) {6668Info.FFDiag(CallRange.getBegin());6669return false;6670}66716672if (!DD || DD->isTrivial() ||6673(RD->isAnonymousStructOrUnion() && RD->isUnion())) {6674// A trivial destructor just ends the lifetime of the object. Check for6675// this case before checking for a body, because we might not bother6676// building a body for a trivial destructor. Note that it doesn't matter6677// whether the destructor is constexpr in this case; all trivial6678// destructors are constexpr.6679//6680// If an anonymous union would be destroyed, some enclosing destructor must6681// have been explicitly defined, and the anonymous union destruction should6682// have no effect.6683Value = APValue();6684return true;6685}66866687if (!Info.CheckCallLimit(CallRange.getBegin()))6688return false;66896690const FunctionDecl *Definition = nullptr;6691const Stmt *Body = DD->getBody(Definition);66926693if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))6694return false;66956696CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,6697CallRef());66986699// We're now in the period of destruction of this object.6700unsigned BasesLeft = RD->getNumBases();6701EvalInfo::EvaluatingDestructorRAII EvalObj(6702Info,6703ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});6704if (!EvalObj.DidInsert) {6705// C++2a [class.dtor]p19:6706// the behavior is undefined if the destructor is invoked for an object6707// whose lifetime has ended6708// (Note that formally the lifetime ends when the period of destruction6709// begins, even though certain uses of the object remain valid until the6710// period of destruction ends.)6711Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);6712return false;6713}67146715// FIXME: Creating an APValue just to hold a nonexistent return value is6716// wasteful.6717APValue RetVal;6718StmtResult Ret = {RetVal, nullptr};6719if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)6720return false;67216722// A union destructor does not implicitly destroy its members.6723if (RD->isUnion())6724return true;67256726const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);67276728// We don't have a good way to iterate fields in reverse, so collect all the6729// fields first and then walk them backwards.6730SmallVector<FieldDecl*, 16> Fields(RD->fields());6731for (const FieldDecl *FD : llvm::reverse(Fields)) {6732if (FD->isUnnamedBitField())6733continue;67346735LValue Subobject = This;6736if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))6737return false;67386739APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());6740if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,6741FD->getType()))6742return false;6743}67446745if (BasesLeft != 0)6746EvalObj.startedDestroyingBases();67476748// Destroy base classes in reverse order.6749for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {6750--BasesLeft;67516752QualType BaseType = Base.getType();6753LValue Subobject = This;6754if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,6755BaseType->getAsCXXRecordDecl(), &Layout))6756return false;67576758APValue *SubobjectValue = &Value.getStructBase(BasesLeft);6759if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,6760BaseType))6761return false;6762}6763assert(BasesLeft == 0 && "NumBases was wrong?");67646765// The period of destruction ends now. The object is gone.6766Value = APValue();6767return true;6768}67696770namespace {6771struct DestroyObjectHandler {6772EvalInfo &Info;6773const Expr *E;6774const LValue &This;6775const AccessKinds AccessKind;67766777typedef bool result_type;6778bool failed() { return false; }6779bool found(APValue &Subobj, QualType SubobjType) {6780return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,6781SubobjType);6782}6783bool found(APSInt &Value, QualType SubobjType) {6784Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);6785return false;6786}6787bool found(APFloat &Value, QualType SubobjType) {6788Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);6789return false;6790}6791};6792}67936794/// Perform a destructor or pseudo-destructor call on the given object, which6795/// might in general not be a complete object.6796static bool HandleDestruction(EvalInfo &Info, const Expr *E,6797const LValue &This, QualType ThisType) {6798CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);6799DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};6800return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);6801}68026803/// Destroy and end the lifetime of the given complete object.6804static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,6805APValue::LValueBase LVBase, APValue &Value,6806QualType T) {6807// If we've had an unmodeled side-effect, we can't rely on mutable state6808// (such as the object we're about to destroy) being correct.6809if (Info.EvalStatus.HasSideEffects)6810return false;68116812LValue LV;6813LV.set({LVBase});6814return HandleDestructionImpl(Info, Loc, LV, Value, T);6815}68166817/// Perform a call to 'operator new' or to `__builtin_operator_new'.6818static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,6819LValue &Result) {6820if (Info.checkingPotentialConstantExpression() ||6821Info.SpeculativeEvaluationDepth)6822return false;68236824// This is permitted only within a call to std::allocator<T>::allocate.6825auto Caller = Info.getStdAllocatorCaller("allocate");6826if (!Caller) {6827Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus206828? diag::note_constexpr_new_untyped6829: diag::note_constexpr_new);6830return false;6831}68326833QualType ElemType = Caller.ElemType;6834if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {6835Info.FFDiag(E->getExprLoc(),6836diag::note_constexpr_new_not_complete_object_type)6837<< (ElemType->isIncompleteType() ? 0 : 1) << ElemType;6838return false;6839}68406841APSInt ByteSize;6842if (!EvaluateInteger(E->getArg(0), ByteSize, Info))6843return false;6844bool IsNothrow = false;6845for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {6846EvaluateIgnoredValue(Info, E->getArg(I));6847IsNothrow |= E->getType()->isNothrowT();6848}68496850CharUnits ElemSize;6851if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))6852return false;6853APInt Size, Remainder;6854APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());6855APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);6856if (Remainder != 0) {6857// This likely indicates a bug in the implementation of 'std::allocator'.6858Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)6859<< ByteSize << APSInt(ElemSizeAP, true) << ElemType;6860return false;6861}68626863if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),6864Size.getZExtValue(), /*Diag=*/!IsNothrow)) {6865if (IsNothrow) {6866Result.setNull(Info.Ctx, E->getType());6867return true;6868}6869return false;6870}68716872QualType AllocType = Info.Ctx.getConstantArrayType(6873ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);6874APValue *Val = Info.createHeapAlloc(E, AllocType, Result);6875*Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());6876Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));6877return true;6878}68796880static bool hasVirtualDestructor(QualType T) {6881if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())6882if (CXXDestructorDecl *DD = RD->getDestructor())6883return DD->isVirtual();6884return false;6885}68866887static const FunctionDecl *getVirtualOperatorDelete(QualType T) {6888if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())6889if (CXXDestructorDecl *DD = RD->getDestructor())6890return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;6891return nullptr;6892}68936894/// Check that the given object is a suitable pointer to a heap allocation that6895/// still exists and is of the right kind for the purpose of a deletion.6896///6897/// On success, returns the heap allocation to deallocate. On failure, produces6898/// a diagnostic and returns std::nullopt.6899static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,6900const LValue &Pointer,6901DynAlloc::Kind DeallocKind) {6902auto PointerAsString = [&] {6903return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);6904};69056906DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();6907if (!DA) {6908Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)6909<< PointerAsString();6910if (Pointer.Base)6911NoteLValueLocation(Info, Pointer.Base);6912return std::nullopt;6913}69146915std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);6916if (!Alloc) {6917Info.FFDiag(E, diag::note_constexpr_double_delete);6918return std::nullopt;6919}69206921if (DeallocKind != (*Alloc)->getKind()) {6922QualType AllocType = Pointer.Base.getDynamicAllocType();6923Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)6924<< DeallocKind << (*Alloc)->getKind() << AllocType;6925NoteLValueLocation(Info, Pointer.Base);6926return std::nullopt;6927}69286929bool Subobject = false;6930if (DeallocKind == DynAlloc::New) {6931Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||6932Pointer.Designator.isOnePastTheEnd();6933} else {6934Subobject = Pointer.Designator.Entries.size() != 1 ||6935Pointer.Designator.Entries[0].getAsArrayIndex() != 0;6936}6937if (Subobject) {6938Info.FFDiag(E, diag::note_constexpr_delete_subobject)6939<< PointerAsString() << Pointer.Designator.isOnePastTheEnd();6940return std::nullopt;6941}69426943return Alloc;6944}69456946// Perform a call to 'operator delete' or '__builtin_operator_delete'.6947bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {6948if (Info.checkingPotentialConstantExpression() ||6949Info.SpeculativeEvaluationDepth)6950return false;69516952// This is permitted only within a call to std::allocator<T>::deallocate.6953if (!Info.getStdAllocatorCaller("deallocate")) {6954Info.FFDiag(E->getExprLoc());6955return true;6956}69576958LValue Pointer;6959if (!EvaluatePointer(E->getArg(0), Pointer, Info))6960return false;6961for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)6962EvaluateIgnoredValue(Info, E->getArg(I));69636964if (Pointer.Designator.Invalid)6965return false;69666967// Deleting a null pointer would have no effect, but it's not permitted by6968// std::allocator<T>::deallocate's contract.6969if (Pointer.isNullPointer()) {6970Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);6971return true;6972}69736974if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))6975return false;69766977Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());6978return true;6979}69806981//===----------------------------------------------------------------------===//6982// Generic Evaluation6983//===----------------------------------------------------------------------===//6984namespace {69856986class BitCastBuffer {6987// FIXME: We're going to need bit-level granularity when we support6988// bit-fields.6989// FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but6990// we don't support a host or target where that is the case. Still, we should6991// use a more generic type in case we ever do.6992SmallVector<std::optional<unsigned char>, 32> Bytes;69936994static_assert(std::numeric_limits<unsigned char>::digits >= 8,6995"Need at least 8 bit unsigned char");69966997bool TargetIsLittleEndian;69986999public:7000BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)7001: Bytes(Width.getQuantity()),7002TargetIsLittleEndian(TargetIsLittleEndian) {}70037004[[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,7005SmallVectorImpl<unsigned char> &Output) const {7006for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {7007// If a byte of an integer is uninitialized, then the whole integer is7008// uninitialized.7009if (!Bytes[I.getQuantity()])7010return false;7011Output.push_back(*Bytes[I.getQuantity()]);7012}7013if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)7014std::reverse(Output.begin(), Output.end());7015return true;7016}70177018void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {7019if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)7020std::reverse(Input.begin(), Input.end());70217022size_t Index = 0;7023for (unsigned char Byte : Input) {7024assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");7025Bytes[Offset.getQuantity() + Index] = Byte;7026++Index;7027}7028}70297030size_t size() { return Bytes.size(); }7031};70327033/// Traverse an APValue to produce an BitCastBuffer, emulating how the current7034/// target would represent the value at runtime.7035class APValueToBufferConverter {7036EvalInfo &Info;7037BitCastBuffer Buffer;7038const CastExpr *BCE;70397040APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,7041const CastExpr *BCE)7042: Info(Info),7043Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),7044BCE(BCE) {}70457046bool visit(const APValue &Val, QualType Ty) {7047return visit(Val, Ty, CharUnits::fromQuantity(0));7048}70497050// Write out Val with type Ty into Buffer starting at Offset.7051bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {7052assert((size_t)Offset.getQuantity() <= Buffer.size());70537054// As a special case, nullptr_t has an indeterminate value.7055if (Ty->isNullPtrType())7056return true;70577058// Dig through Src to find the byte at SrcOffset.7059switch (Val.getKind()) {7060case APValue::Indeterminate:7061case APValue::None:7062return true;70637064case APValue::Int:7065return visitInt(Val.getInt(), Ty, Offset);7066case APValue::Float:7067return visitFloat(Val.getFloat(), Ty, Offset);7068case APValue::Array:7069return visitArray(Val, Ty, Offset);7070case APValue::Struct:7071return visitRecord(Val, Ty, Offset);7072case APValue::Vector:7073return visitVector(Val, Ty, Offset);70747075case APValue::ComplexInt:7076case APValue::ComplexFloat:7077case APValue::FixedPoint:7078// FIXME: We should support these.70797080case APValue::Union:7081case APValue::MemberPointer:7082case APValue::AddrLabelDiff: {7083Info.FFDiag(BCE->getBeginLoc(),7084diag::note_constexpr_bit_cast_unsupported_type)7085<< Ty;7086return false;7087}70887089case APValue::LValue:7090llvm_unreachable("LValue subobject in bit_cast?");7091}7092llvm_unreachable("Unhandled APValue::ValueKind");7093}70947095bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {7096const RecordDecl *RD = Ty->getAsRecordDecl();7097const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);70987099// Visit the base classes.7100if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {7101for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {7102const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];7103CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();71047105if (!visitRecord(Val.getStructBase(I), BS.getType(),7106Layout.getBaseClassOffset(BaseDecl) + Offset))7107return false;7108}7109}71107111// Visit the fields.7112unsigned FieldIdx = 0;7113for (FieldDecl *FD : RD->fields()) {7114if (FD->isBitField()) {7115Info.FFDiag(BCE->getBeginLoc(),7116diag::note_constexpr_bit_cast_unsupported_bitfield);7117return false;7118}71197120uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);71217122assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&7123"only bit-fields can have sub-char alignment");7124CharUnits FieldOffset =7125Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;7126QualType FieldTy = FD->getType();7127if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))7128return false;7129++FieldIdx;7130}71317132return true;7133}71347135bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {7136const auto *CAT =7137dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());7138if (!CAT)7139return false;71407141CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());7142unsigned NumInitializedElts = Val.getArrayInitializedElts();7143unsigned ArraySize = Val.getArraySize();7144// First, initialize the initialized elements.7145for (unsigned I = 0; I != NumInitializedElts; ++I) {7146const APValue &SubObj = Val.getArrayInitializedElt(I);7147if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))7148return false;7149}71507151// Next, initialize the rest of the array using the filler.7152if (Val.hasArrayFiller()) {7153const APValue &Filler = Val.getArrayFiller();7154for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {7155if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))7156return false;7157}7158}71597160return true;7161}71627163bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {7164const VectorType *VTy = Ty->castAs<VectorType>();7165QualType EltTy = VTy->getElementType();7166unsigned NElts = VTy->getNumElements();7167unsigned EltSize =7168VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);71697170if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {7171// The vector's size in bits is not a multiple of the target's byte size,7172// so its layout is unspecified. For now, we'll simply treat these cases7173// as unsupported (this should only be possible with OpenCL bool vectors7174// whose element count isn't a multiple of the byte size).7175Info.FFDiag(BCE->getBeginLoc(),7176diag::note_constexpr_bit_cast_invalid_vector)7177<< Ty.getCanonicalType() << EltSize << NElts7178<< Info.Ctx.getCharWidth();7179return false;7180}71817182if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==7183&APFloat::x87DoubleExtended()) {7184// The layout for x86_fp80 vectors seems to be handled very inconsistently7185// by both clang and LLVM, so for now we won't allow bit_casts involving7186// it in a constexpr context.7187Info.FFDiag(BCE->getBeginLoc(),7188diag::note_constexpr_bit_cast_unsupported_type)7189<< EltTy;7190return false;7191}71927193if (VTy->isExtVectorBoolType()) {7194// Special handling for OpenCL bool vectors:7195// Since these vectors are stored as packed bits, but we can't write7196// individual bits to the BitCastBuffer, we'll buffer all of the elements7197// together into an appropriately sized APInt and write them all out at7198// once. Because we don't accept vectors where NElts * EltSize isn't a7199// multiple of the char size, there will be no padding space, so we don't7200// have to worry about writing data which should have been left7201// uninitialized.7202bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();72037204llvm::APInt Res = llvm::APInt::getZero(NElts);7205for (unsigned I = 0; I < NElts; ++I) {7206const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();7207assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&7208"bool vector element must be 1-bit unsigned integer!");72097210Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);7211}72127213SmallVector<uint8_t, 8> Bytes(NElts / 8);7214llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);7215Buffer.writeObject(Offset, Bytes);7216} else {7217// Iterate over each of the elements and write them out to the buffer at7218// the appropriate offset.7219CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);7220for (unsigned I = 0; I < NElts; ++I) {7221if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))7222return false;7223}7224}72257226return true;7227}72287229bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {7230APSInt AdjustedVal = Val;7231unsigned Width = AdjustedVal.getBitWidth();7232if (Ty->isBooleanType()) {7233Width = Info.Ctx.getTypeSize(Ty);7234AdjustedVal = AdjustedVal.extend(Width);7235}72367237SmallVector<uint8_t, 8> Bytes(Width / 8);7238llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);7239Buffer.writeObject(Offset, Bytes);7240return true;7241}72427243bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {7244APSInt AsInt(Val.bitcastToAPInt());7245return visitInt(AsInt, Ty, Offset);7246}72477248public:7249static std::optional<BitCastBuffer>7250convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {7251CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());7252APValueToBufferConverter Converter(Info, DstSize, BCE);7253if (!Converter.visit(Src, BCE->getSubExpr()->getType()))7254return std::nullopt;7255return Converter.Buffer;7256}7257};72587259/// Write an BitCastBuffer into an APValue.7260class BufferToAPValueConverter {7261EvalInfo &Info;7262const BitCastBuffer &Buffer;7263const CastExpr *BCE;72647265BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,7266const CastExpr *BCE)7267: Info(Info), Buffer(Buffer), BCE(BCE) {}72687269// Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast7270// with an invalid type, so anything left is a deficiency on our part (FIXME).7271// Ideally this will be unreachable.7272std::nullopt_t unsupportedType(QualType Ty) {7273Info.FFDiag(BCE->getBeginLoc(),7274diag::note_constexpr_bit_cast_unsupported_type)7275<< Ty;7276return std::nullopt;7277}72787279std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {7280Info.FFDiag(BCE->getBeginLoc(),7281diag::note_constexpr_bit_cast_unrepresentable_value)7282<< Ty << toString(Val, /*Radix=*/10);7283return std::nullopt;7284}72857286std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,7287const EnumType *EnumSugar = nullptr) {7288if (T->isNullPtrType()) {7289uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));7290return APValue((Expr *)nullptr,7291/*Offset=*/CharUnits::fromQuantity(NullValue),7292APValue::NoLValuePath{}, /*IsNullPtr=*/true);7293}72947295CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);72967297// Work around floating point types that contain unused padding bytes. This7298// is really just `long double` on x86, which is the only fundamental type7299// with padding bytes.7300if (T->isRealFloatingType()) {7301const llvm::fltSemantics &Semantics =7302Info.Ctx.getFloatTypeSemantics(QualType(T, 0));7303unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);7304assert(NumBits % 8 == 0);7305CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);7306if (NumBytes != SizeOf)7307SizeOf = NumBytes;7308}73097310SmallVector<uint8_t, 8> Bytes;7311if (!Buffer.readObject(Offset, SizeOf, Bytes)) {7312// If this is std::byte or unsigned char, then its okay to store an7313// indeterminate value.7314bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();7315bool IsUChar =7316!EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||7317T->isSpecificBuiltinType(BuiltinType::Char_U));7318if (!IsStdByte && !IsUChar) {7319QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);7320Info.FFDiag(BCE->getExprLoc(),7321diag::note_constexpr_bit_cast_indet_dest)7322<< DisplayType << Info.Ctx.getLangOpts().CharIsSigned;7323return std::nullopt;7324}73257326return APValue::IndeterminateValue();7327}73287329APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);7330llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());73317332if (T->isIntegralOrEnumerationType()) {7333Val.setIsSigned(T->isSignedIntegerOrEnumerationType());73347335unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));7336if (IntWidth != Val.getBitWidth()) {7337APSInt Truncated = Val.trunc(IntWidth);7338if (Truncated.extend(Val.getBitWidth()) != Val)7339return unrepresentableValue(QualType(T, 0), Val);7340Val = Truncated;7341}73427343return APValue(Val);7344}73457346if (T->isRealFloatingType()) {7347const llvm::fltSemantics &Semantics =7348Info.Ctx.getFloatTypeSemantics(QualType(T, 0));7349return APValue(APFloat(Semantics, Val));7350}73517352return unsupportedType(QualType(T, 0));7353}73547355std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {7356const RecordDecl *RD = RTy->getAsRecordDecl();7357const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);73587359unsigned NumBases = 0;7360if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))7361NumBases = CXXRD->getNumBases();73627363APValue ResultVal(APValue::UninitStruct(), NumBases,7364std::distance(RD->field_begin(), RD->field_end()));73657366// Visit the base classes.7367if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {7368for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {7369const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];7370CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();73717372std::optional<APValue> SubObj = visitType(7373BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);7374if (!SubObj)7375return std::nullopt;7376ResultVal.getStructBase(I) = *SubObj;7377}7378}73797380// Visit the fields.7381unsigned FieldIdx = 0;7382for (FieldDecl *FD : RD->fields()) {7383// FIXME: We don't currently support bit-fields. A lot of the logic for7384// this is in CodeGen, so we need to factor it around.7385if (FD->isBitField()) {7386Info.FFDiag(BCE->getBeginLoc(),7387diag::note_constexpr_bit_cast_unsupported_bitfield);7388return std::nullopt;7389}73907391uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);7392assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);73937394CharUnits FieldOffset =7395CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +7396Offset;7397QualType FieldTy = FD->getType();7398std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);7399if (!SubObj)7400return std::nullopt;7401ResultVal.getStructField(FieldIdx) = *SubObj;7402++FieldIdx;7403}74047405return ResultVal;7406}74077408std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {7409QualType RepresentationType = Ty->getDecl()->getIntegerType();7410assert(!RepresentationType.isNull() &&7411"enum forward decl should be caught by Sema");7412const auto *AsBuiltin =7413RepresentationType.getCanonicalType()->castAs<BuiltinType>();7414// Recurse into the underlying type. Treat std::byte transparently as7415// unsigned char.7416return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);7417}74187419std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {7420size_t Size = Ty->getLimitedSize();7421CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());74227423APValue ArrayValue(APValue::UninitArray(), Size, Size);7424for (size_t I = 0; I != Size; ++I) {7425std::optional<APValue> ElementValue =7426visitType(Ty->getElementType(), Offset + I * ElementWidth);7427if (!ElementValue)7428return std::nullopt;7429ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);7430}74317432return ArrayValue;7433}74347435std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {7436QualType EltTy = VTy->getElementType();7437unsigned NElts = VTy->getNumElements();7438unsigned EltSize =7439VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);74407441if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {7442// The vector's size in bits is not a multiple of the target's byte size,7443// so its layout is unspecified. For now, we'll simply treat these cases7444// as unsupported (this should only be possible with OpenCL bool vectors7445// whose element count isn't a multiple of the byte size).7446Info.FFDiag(BCE->getBeginLoc(),7447diag::note_constexpr_bit_cast_invalid_vector)7448<< QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();7449return std::nullopt;7450}74517452if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==7453&APFloat::x87DoubleExtended()) {7454// The layout for x86_fp80 vectors seems to be handled very inconsistently7455// by both clang and LLVM, so for now we won't allow bit_casts involving7456// it in a constexpr context.7457Info.FFDiag(BCE->getBeginLoc(),7458diag::note_constexpr_bit_cast_unsupported_type)7459<< EltTy;7460return std::nullopt;7461}74627463SmallVector<APValue, 4> Elts;7464Elts.reserve(NElts);7465if (VTy->isExtVectorBoolType()) {7466// Special handling for OpenCL bool vectors:7467// Since these vectors are stored as packed bits, but we can't read7468// individual bits from the BitCastBuffer, we'll buffer all of the7469// elements together into an appropriately sized APInt and write them all7470// out at once. Because we don't accept vectors where NElts * EltSize7471// isn't a multiple of the char size, there will be no padding space, so7472// we don't have to worry about reading any padding data which didn't7473// actually need to be accessed.7474bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();74757476SmallVector<uint8_t, 8> Bytes;7477Bytes.reserve(NElts / 8);7478if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))7479return std::nullopt;74807481APSInt SValInt(NElts, true);7482llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());74837484for (unsigned I = 0; I < NElts; ++I) {7485llvm::APInt Elt =7486SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);7487Elts.emplace_back(7488APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));7489}7490} else {7491// Iterate over each of the elements and read them from the buffer at7492// the appropriate offset.7493CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);7494for (unsigned I = 0; I < NElts; ++I) {7495std::optional<APValue> EltValue =7496visitType(EltTy, Offset + I * EltSizeChars);7497if (!EltValue)7498return std::nullopt;7499Elts.push_back(std::move(*EltValue));7500}7501}75027503return APValue(Elts.data(), Elts.size());7504}75057506std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {7507return unsupportedType(QualType(Ty, 0));7508}75097510std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {7511QualType Can = Ty.getCanonicalType();75127513switch (Can->getTypeClass()) {7514#define TYPE(Class, Base) \7515case Type::Class: \7516return visit(cast<Class##Type>(Can.getTypePtr()), Offset);7517#define ABSTRACT_TYPE(Class, Base)7518#define NON_CANONICAL_TYPE(Class, Base) \7519case Type::Class: \7520llvm_unreachable("non-canonical type should be impossible!");7521#define DEPENDENT_TYPE(Class, Base) \7522case Type::Class: \7523llvm_unreachable( \7524"dependent types aren't supported in the constant evaluator!");7525#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \7526case Type::Class: \7527llvm_unreachable("either dependent or not canonical!");7528#include "clang/AST/TypeNodes.inc"7529}7530llvm_unreachable("Unhandled Type::TypeClass");7531}75327533public:7534// Pull out a full value of type DstType.7535static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,7536const CastExpr *BCE) {7537BufferToAPValueConverter Converter(Info, Buffer, BCE);7538return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));7539}7540};75417542static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,7543QualType Ty, EvalInfo *Info,7544const ASTContext &Ctx,7545bool CheckingDest) {7546Ty = Ty.getCanonicalType();75477548auto diag = [&](int Reason) {7549if (Info)7550Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)7551<< CheckingDest << (Reason == 4) << Reason;7552return false;7553};7554auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {7555if (Info)7556Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)7557<< NoteTy << Construct << Ty;7558return false;7559};75607561if (Ty->isUnionType())7562return diag(0);7563if (Ty->isPointerType())7564return diag(1);7565if (Ty->isMemberPointerType())7566return diag(2);7567if (Ty.isVolatileQualified())7568return diag(3);75697570if (RecordDecl *Record = Ty->getAsRecordDecl()) {7571if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {7572for (CXXBaseSpecifier &BS : CXXRD->bases())7573if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,7574CheckingDest))7575return note(1, BS.getType(), BS.getBeginLoc());7576}7577for (FieldDecl *FD : Record->fields()) {7578if (FD->getType()->isReferenceType())7579return diag(4);7580if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,7581CheckingDest))7582return note(0, FD->getType(), FD->getBeginLoc());7583}7584}75857586if (Ty->isArrayType() &&7587!checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),7588Info, Ctx, CheckingDest))7589return false;75907591return true;7592}75937594static bool checkBitCastConstexprEligibility(EvalInfo *Info,7595const ASTContext &Ctx,7596const CastExpr *BCE) {7597bool DestOK = checkBitCastConstexprEligibilityType(7598BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);7599bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(7600BCE->getBeginLoc(),7601BCE->getSubExpr()->getType(), Info, Ctx, false);7602return SourceOK;7603}76047605static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,7606const APValue &SourceRValue,7607const CastExpr *BCE) {7608assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&7609"no host or target supports non 8-bit chars");76107611if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))7612return false;76137614// Read out SourceValue into a char buffer.7615std::optional<BitCastBuffer> Buffer =7616APValueToBufferConverter::convert(Info, SourceRValue, BCE);7617if (!Buffer)7618return false;76197620// Write out the buffer into a new APValue.7621std::optional<APValue> MaybeDestValue =7622BufferToAPValueConverter::convert(Info, *Buffer, BCE);7623if (!MaybeDestValue)7624return false;76257626DestValue = std::move(*MaybeDestValue);7627return true;7628}76297630static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,7631APValue &SourceValue,7632const CastExpr *BCE) {7633assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&7634"no host or target supports non 8-bit chars");7635assert(SourceValue.isLValue() &&7636"LValueToRValueBitcast requires an lvalue operand!");76377638LValue SourceLValue;7639APValue SourceRValue;7640SourceLValue.setFrom(Info.Ctx, SourceValue);7641if (!handleLValueToRValueConversion(7642Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,7643SourceRValue, /*WantObjectRepresentation=*/true))7644return false;76457646return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);7647}76487649template <class Derived>7650class ExprEvaluatorBase7651: public ConstStmtVisitor<Derived, bool> {7652private:7653Derived &getDerived() { return static_cast<Derived&>(*this); }7654bool DerivedSuccess(const APValue &V, const Expr *E) {7655return getDerived().Success(V, E);7656}7657bool DerivedZeroInitialization(const Expr *E) {7658return getDerived().ZeroInitialization(E);7659}76607661// Check whether a conditional operator with a non-constant condition is a7662// potential constant expression. If neither arm is a potential constant7663// expression, then the conditional operator is not either.7664template<typename ConditionalOperator>7665void CheckPotentialConstantConditional(const ConditionalOperator *E) {7666assert(Info.checkingPotentialConstantExpression());76677668// Speculatively evaluate both arms.7669SmallVector<PartialDiagnosticAt, 8> Diag;7670{7671SpeculativeEvaluationRAII Speculate(Info, &Diag);7672StmtVisitorTy::Visit(E->getFalseExpr());7673if (Diag.empty())7674return;7675}76767677{7678SpeculativeEvaluationRAII Speculate(Info, &Diag);7679Diag.clear();7680StmtVisitorTy::Visit(E->getTrueExpr());7681if (Diag.empty())7682return;7683}76847685Error(E, diag::note_constexpr_conditional_never_const);7686}768776887689template<typename ConditionalOperator>7690bool HandleConditionalOperator(const ConditionalOperator *E) {7691bool BoolResult;7692if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {7693if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {7694CheckPotentialConstantConditional(E);7695return false;7696}7697if (Info.noteFailure()) {7698StmtVisitorTy::Visit(E->getTrueExpr());7699StmtVisitorTy::Visit(E->getFalseExpr());7700}7701return false;7702}77037704Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();7705return StmtVisitorTy::Visit(EvalExpr);7706}77077708protected:7709EvalInfo &Info;7710typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;7711typedef ExprEvaluatorBase ExprEvaluatorBaseTy;77127713OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {7714return Info.CCEDiag(E, D);7715}77167717bool ZeroInitialization(const Expr *E) { return Error(E); }77187719bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {7720unsigned BuiltinOp = E->getBuiltinCallee();7721return BuiltinOp != 0 &&7722Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);7723}77247725public:7726ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}77277728EvalInfo &getEvalInfo() { return Info; }77297730/// Report an evaluation error. This should only be called when an error is7731/// first discovered. When propagating an error, just return false.7732bool Error(const Expr *E, diag::kind D) {7733Info.FFDiag(E, D) << E->getSourceRange();7734return false;7735}7736bool Error(const Expr *E) {7737return Error(E, diag::note_invalid_subexpr_in_const_expr);7738}77397740bool VisitStmt(const Stmt *) {7741llvm_unreachable("Expression evaluator should not be called on stmts");7742}7743bool VisitExpr(const Expr *E) {7744return Error(E);7745}77467747bool VisitEmbedExpr(const EmbedExpr *E) {7748const auto It = E->begin();7749return StmtVisitorTy::Visit(*It);7750}77517752bool VisitPredefinedExpr(const PredefinedExpr *E) {7753return StmtVisitorTy::Visit(E->getFunctionName());7754}7755bool VisitConstantExpr(const ConstantExpr *E) {7756if (E->hasAPValueResult())7757return DerivedSuccess(E->getAPValueResult(), E);77587759return StmtVisitorTy::Visit(E->getSubExpr());7760}77617762bool VisitParenExpr(const ParenExpr *E)7763{ return StmtVisitorTy::Visit(E->getSubExpr()); }7764bool VisitUnaryExtension(const UnaryOperator *E)7765{ return StmtVisitorTy::Visit(E->getSubExpr()); }7766bool VisitUnaryPlus(const UnaryOperator *E)7767{ return StmtVisitorTy::Visit(E->getSubExpr()); }7768bool VisitChooseExpr(const ChooseExpr *E)7769{ return StmtVisitorTy::Visit(E->getChosenSubExpr()); }7770bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)7771{ return StmtVisitorTy::Visit(E->getResultExpr()); }7772bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)7773{ return StmtVisitorTy::Visit(E->getReplacement()); }7774bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {7775TempVersionRAII RAII(*Info.CurrentCall);7776SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);7777return StmtVisitorTy::Visit(E->getExpr());7778}7779bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {7780TempVersionRAII RAII(*Info.CurrentCall);7781// The initializer may not have been parsed yet, or might be erroneous.7782if (!E->getExpr())7783return Error(E);7784SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);7785return StmtVisitorTy::Visit(E->getExpr());7786}77877788bool VisitExprWithCleanups(const ExprWithCleanups *E) {7789FullExpressionRAII Scope(Info);7790return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();7791}77927793// Temporaries are registered when created, so we don't care about7794// CXXBindTemporaryExpr.7795bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {7796return StmtVisitorTy::Visit(E->getSubExpr());7797}77987799bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {7800CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;7801return static_cast<Derived*>(this)->VisitCastExpr(E);7802}7803bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {7804if (!Info.Ctx.getLangOpts().CPlusPlus20)7805CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;7806return static_cast<Derived*>(this)->VisitCastExpr(E);7807}7808bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {7809return static_cast<Derived*>(this)->VisitCastExpr(E);7810}78117812bool VisitBinaryOperator(const BinaryOperator *E) {7813switch (E->getOpcode()) {7814default:7815return Error(E);78167817case BO_Comma:7818VisitIgnoredValue(E->getLHS());7819return StmtVisitorTy::Visit(E->getRHS());78207821case BO_PtrMemD:7822case BO_PtrMemI: {7823LValue Obj;7824if (!HandleMemberPointerAccess(Info, E, Obj))7825return false;7826APValue Result;7827if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))7828return false;7829return DerivedSuccess(Result, E);7830}7831}7832}78337834bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {7835return StmtVisitorTy::Visit(E->getSemanticForm());7836}78377838bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {7839// Evaluate and cache the common expression. We treat it as a temporary,7840// even though it's not quite the same thing.7841LValue CommonLV;7842if (!Evaluate(Info.CurrentCall->createTemporary(7843E->getOpaqueValue(),7844getStorageType(Info.Ctx, E->getOpaqueValue()),7845ScopeKind::FullExpression, CommonLV),7846Info, E->getCommon()))7847return false;78487849return HandleConditionalOperator(E);7850}78517852bool VisitConditionalOperator(const ConditionalOperator *E) {7853bool IsBcpCall = false;7854// If the condition (ignoring parens) is a __builtin_constant_p call,7855// the result is a constant expression if it can be folded without7856// side-effects. This is an important GNU extension. See GCC PR383777857// for discussion.7858if (const CallExpr *CallCE =7859dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))7860if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)7861IsBcpCall = true;78627863// Always assume __builtin_constant_p(...) ? ... : ... is a potential7864// constant expression; we can't check whether it's potentially foldable.7865// FIXME: We should instead treat __builtin_constant_p as non-constant if7866// it would return 'false' in this mode.7867if (Info.checkingPotentialConstantExpression() && IsBcpCall)7868return false;78697870FoldConstant Fold(Info, IsBcpCall);7871if (!HandleConditionalOperator(E)) {7872Fold.keepDiagnostics();7873return false;7874}78757876return true;7877}78787879bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {7880if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);7881Value && !Value->isAbsent())7882return DerivedSuccess(*Value, E);78837884const Expr *Source = E->getSourceExpr();7885if (!Source)7886return Error(E);7887if (Source == E) {7888assert(0 && "OpaqueValueExpr recursively refers to itself");7889return Error(E);7890}7891return StmtVisitorTy::Visit(Source);7892}78937894bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {7895for (const Expr *SemE : E->semantics()) {7896if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {7897// FIXME: We can't handle the case where an OpaqueValueExpr is also the7898// result expression: there could be two different LValues that would7899// refer to the same object in that case, and we can't model that.7900if (SemE == E->getResultExpr())7901return Error(E);79027903// Unique OVEs get evaluated if and when we encounter them when7904// emitting the rest of the semantic form, rather than eagerly.7905if (OVE->isUnique())7906continue;79077908LValue LV;7909if (!Evaluate(Info.CurrentCall->createTemporary(7910OVE, getStorageType(Info.Ctx, OVE),7911ScopeKind::FullExpression, LV),7912Info, OVE->getSourceExpr()))7913return false;7914} else if (SemE == E->getResultExpr()) {7915if (!StmtVisitorTy::Visit(SemE))7916return false;7917} else {7918if (!EvaluateIgnoredValue(Info, SemE))7919return false;7920}7921}7922return true;7923}79247925bool VisitCallExpr(const CallExpr *E) {7926APValue Result;7927if (!handleCallExpr(E, Result, nullptr))7928return false;7929return DerivedSuccess(Result, E);7930}79317932bool handleCallExpr(const CallExpr *E, APValue &Result,7933const LValue *ResultSlot) {7934CallScopeRAII CallScope(Info);79357936const Expr *Callee = E->getCallee()->IgnoreParens();7937QualType CalleeType = Callee->getType();79387939const FunctionDecl *FD = nullptr;7940LValue *This = nullptr, ThisVal;7941auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());7942bool HasQualifier = false;79437944CallRef Call;79457946// Extract function decl and 'this' pointer from the callee.7947if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {7948const CXXMethodDecl *Member = nullptr;7949if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {7950// Explicit bound member calls, such as x.f() or p->g();7951if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))7952return false;7953Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());7954if (!Member)7955return Error(Callee);7956This = &ThisVal;7957HasQualifier = ME->hasQualifier();7958} else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {7959// Indirect bound member calls ('.*' or '->*').7960const ValueDecl *D =7961HandleMemberPointerAccess(Info, BE, ThisVal, false);7962if (!D)7963return false;7964Member = dyn_cast<CXXMethodDecl>(D);7965if (!Member)7966return Error(Callee);7967This = &ThisVal;7968} else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {7969if (!Info.getLangOpts().CPlusPlus20)7970Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);7971return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&7972HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());7973} else7974return Error(Callee);7975FD = Member;7976} else if (CalleeType->isFunctionPointerType()) {7977LValue CalleeLV;7978if (!EvaluatePointer(Callee, CalleeLV, Info))7979return false;79807981if (!CalleeLV.getLValueOffset().isZero())7982return Error(Callee);7983if (CalleeLV.isNullPointer()) {7984Info.FFDiag(Callee, diag::note_constexpr_null_callee)7985<< const_cast<Expr *>(Callee);7986return false;7987}7988FD = dyn_cast_or_null<FunctionDecl>(7989CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());7990if (!FD)7991return Error(Callee);7992// Don't call function pointers which have been cast to some other type.7993// Per DR (no number yet), the caller and callee can differ in noexcept.7994if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(7995CalleeType->getPointeeType(), FD->getType())) {7996return Error(E);7997}79987999// For an (overloaded) assignment expression, evaluate the RHS before the8000// LHS.8001auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);8002if (OCE && OCE->isAssignmentOp()) {8003assert(Args.size() == 2 && "wrong number of arguments in assignment");8004Call = Info.CurrentCall->createCall(FD);8005bool HasThis = false;8006if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))8007HasThis = MD->isImplicitObjectMemberFunction();8008if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,8009/*RightToLeft=*/true))8010return false;8011}80128013// Overloaded operator calls to member functions are represented as normal8014// calls with '*this' as the first argument.8015const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);8016if (MD &&8017(MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {8018// FIXME: When selecting an implicit conversion for an overloaded8019// operator delete, we sometimes try to evaluate calls to conversion8020// operators without a 'this' parameter!8021if (Args.empty())8022return Error(E);80238024if (!EvaluateObjectArgument(Info, Args[0], ThisVal))8025return false;80268027// If we are calling a static operator, the 'this' argument needs to be8028// ignored after being evaluated.8029if (MD->isInstance())8030This = &ThisVal;80318032// If this is syntactically a simple assignment using a trivial8033// assignment operator, start the lifetimes of union members as needed,8034// per C++20 [class.union]5.8035if (Info.getLangOpts().CPlusPlus20 && OCE &&8036OCE->getOperator() == OO_Equal && MD->isTrivial() &&8037!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))8038return false;80398040Args = Args.slice(1);8041} else if (MD && MD->isLambdaStaticInvoker()) {8042// Map the static invoker for the lambda back to the call operator.8043// Conveniently, we don't have to slice out the 'this' argument (as is8044// being done for the non-static case), since a static member function8045// doesn't have an implicit argument passed in.8046const CXXRecordDecl *ClosureClass = MD->getParent();8047assert(8048ClosureClass->captures_begin() == ClosureClass->captures_end() &&8049"Number of captures must be zero for conversion to function-ptr");80508051const CXXMethodDecl *LambdaCallOp =8052ClosureClass->getLambdaCallOperator();80538054// Set 'FD', the function that will be called below, to the call8055// operator. If the closure object represents a generic lambda, find8056// the corresponding specialization of the call operator.80578058if (ClosureClass->isGenericLambda()) {8059assert(MD->isFunctionTemplateSpecialization() &&8060"A generic lambda's static-invoker function must be a "8061"template specialization");8062const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();8063FunctionTemplateDecl *CallOpTemplate =8064LambdaCallOp->getDescribedFunctionTemplate();8065void *InsertPos = nullptr;8066FunctionDecl *CorrespondingCallOpSpecialization =8067CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);8068assert(CorrespondingCallOpSpecialization &&8069"We must always have a function call operator specialization "8070"that corresponds to our static invoker specialization");8071assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));8072FD = CorrespondingCallOpSpecialization;8073} else8074FD = LambdaCallOp;8075} else if (FD->isReplaceableGlobalAllocationFunction()) {8076if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||8077FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {8078LValue Ptr;8079if (!HandleOperatorNewCall(Info, E, Ptr))8080return false;8081Ptr.moveInto(Result);8082return CallScope.destroy();8083} else {8084return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();8085}8086}8087} else8088return Error(E);80898090// Evaluate the arguments now if we've not already done so.8091if (!Call) {8092Call = Info.CurrentCall->createCall(FD);8093if (!EvaluateArgs(Args, Call, Info, FD))8094return false;8095}80968097SmallVector<QualType, 4> CovariantAdjustmentPath;8098if (This) {8099auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);8100if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {8101// Perform virtual dispatch, if necessary.8102FD = HandleVirtualDispatch(Info, E, *This, NamedMember,8103CovariantAdjustmentPath);8104if (!FD)8105return false;8106} else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {8107// Check that the 'this' pointer points to an object of the right type.8108// FIXME: If this is an assignment operator call, we may need to change8109// the active union member before we check this.8110if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))8111return false;8112}8113}81148115// Destructor calls are different enough that they have their own codepath.8116if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {8117assert(This && "no 'this' pointer for destructor call");8118return HandleDestruction(Info, E, *This,8119Info.Ctx.getRecordType(DD->getParent())) &&8120CallScope.destroy();8121}81228123const FunctionDecl *Definition = nullptr;8124Stmt *Body = FD->getBody(Definition);81258126if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||8127!HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,8128Body, Info, Result, ResultSlot))8129return false;81308131if (!CovariantAdjustmentPath.empty() &&8132!HandleCovariantReturnAdjustment(Info, E, Result,8133CovariantAdjustmentPath))8134return false;81358136return CallScope.destroy();8137}81388139bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {8140return StmtVisitorTy::Visit(E->getInitializer());8141}8142bool VisitInitListExpr(const InitListExpr *E) {8143if (E->getNumInits() == 0)8144return DerivedZeroInitialization(E);8145if (E->getNumInits() == 1)8146return StmtVisitorTy::Visit(E->getInit(0));8147return Error(E);8148}8149bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {8150return DerivedZeroInitialization(E);8151}8152bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {8153return DerivedZeroInitialization(E);8154}8155bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {8156return DerivedZeroInitialization(E);8157}81588159/// A member expression where the object is a prvalue is itself a prvalue.8160bool VisitMemberExpr(const MemberExpr *E) {8161assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&8162"missing temporary materialization conversion");8163assert(!E->isArrow() && "missing call to bound member function?");81648165APValue Val;8166if (!Evaluate(Val, Info, E->getBase()))8167return false;81688169QualType BaseTy = E->getBase()->getType();81708171const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());8172if (!FD) return Error(E);8173assert(!FD->getType()->isReferenceType() && "prvalue reference?");8174assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==8175FD->getParent()->getCanonicalDecl() && "record / field mismatch");81768177// Note: there is no lvalue base here. But this case should only ever8178// happen in C or in C++98, where we cannot be evaluating a constexpr8179// constructor, which is the only case the base matters.8180CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);8181SubobjectDesignator Designator(BaseTy);8182Designator.addDeclUnchecked(FD);81838184APValue Result;8185return extractSubobject(Info, E, Obj, Designator, Result) &&8186DerivedSuccess(Result, E);8187}81888189bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {8190APValue Val;8191if (!Evaluate(Val, Info, E->getBase()))8192return false;81938194if (Val.isVector()) {8195SmallVector<uint32_t, 4> Indices;8196E->getEncodedElementAccess(Indices);8197if (Indices.size() == 1) {8198// Return scalar.8199return DerivedSuccess(Val.getVectorElt(Indices[0]), E);8200} else {8201// Construct new APValue vector.8202SmallVector<APValue, 4> Elts;8203for (unsigned I = 0; I < Indices.size(); ++I) {8204Elts.push_back(Val.getVectorElt(Indices[I]));8205}8206APValue VecResult(Elts.data(), Indices.size());8207return DerivedSuccess(VecResult, E);8208}8209}82108211return false;8212}82138214bool VisitCastExpr(const CastExpr *E) {8215switch (E->getCastKind()) {8216default:8217break;82188219case CK_AtomicToNonAtomic: {8220APValue AtomicVal;8221// This does not need to be done in place even for class/array types:8222// atomic-to-non-atomic conversion implies copying the object8223// representation.8224if (!Evaluate(AtomicVal, Info, E->getSubExpr()))8225return false;8226return DerivedSuccess(AtomicVal, E);8227}82288229case CK_NoOp:8230case CK_UserDefinedConversion:8231return StmtVisitorTy::Visit(E->getSubExpr());82328233case CK_LValueToRValue: {8234LValue LVal;8235if (!EvaluateLValue(E->getSubExpr(), LVal, Info))8236return false;8237APValue RVal;8238// Note, we use the subexpression's type in order to retain cv-qualifiers.8239if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),8240LVal, RVal))8241return false;8242return DerivedSuccess(RVal, E);8243}8244case CK_LValueToRValueBitCast: {8245APValue DestValue, SourceValue;8246if (!Evaluate(SourceValue, Info, E->getSubExpr()))8247return false;8248if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))8249return false;8250return DerivedSuccess(DestValue, E);8251}82528253case CK_AddressSpaceConversion: {8254APValue Value;8255if (!Evaluate(Value, Info, E->getSubExpr()))8256return false;8257return DerivedSuccess(Value, E);8258}8259}82608261return Error(E);8262}82638264bool VisitUnaryPostInc(const UnaryOperator *UO) {8265return VisitUnaryPostIncDec(UO);8266}8267bool VisitUnaryPostDec(const UnaryOperator *UO) {8268return VisitUnaryPostIncDec(UO);8269}8270bool VisitUnaryPostIncDec(const UnaryOperator *UO) {8271if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())8272return Error(UO);82738274LValue LVal;8275if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))8276return false;8277APValue RVal;8278if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),8279UO->isIncrementOp(), &RVal))8280return false;8281return DerivedSuccess(RVal, UO);8282}82838284bool VisitStmtExpr(const StmtExpr *E) {8285// We will have checked the full-expressions inside the statement expression8286// when they were completed, and don't need to check them again now.8287llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,8288false);82898290const CompoundStmt *CS = E->getSubStmt();8291if (CS->body_empty())8292return true;82938294BlockScopeRAII Scope(Info);8295for (CompoundStmt::const_body_iterator BI = CS->body_begin(),8296BE = CS->body_end();8297/**/; ++BI) {8298if (BI + 1 == BE) {8299const Expr *FinalExpr = dyn_cast<Expr>(*BI);8300if (!FinalExpr) {8301Info.FFDiag((*BI)->getBeginLoc(),8302diag::note_constexpr_stmt_expr_unsupported);8303return false;8304}8305return this->Visit(FinalExpr) && Scope.destroy();8306}83078308APValue ReturnValue;8309StmtResult Result = { ReturnValue, nullptr };8310EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);8311if (ESR != ESR_Succeeded) {8312// FIXME: If the statement-expression terminated due to 'return',8313// 'break', or 'continue', it would be nice to propagate that to8314// the outer statement evaluation rather than bailing out.8315if (ESR != ESR_Failed)8316Info.FFDiag((*BI)->getBeginLoc(),8317diag::note_constexpr_stmt_expr_unsupported);8318return false;8319}8320}83218322llvm_unreachable("Return from function from the loop above.");8323}83248325bool VisitPackIndexingExpr(const PackIndexingExpr *E) {8326return StmtVisitorTy::Visit(E->getSelectedExpr());8327}83288329/// Visit a value which is evaluated, but whose value is ignored.8330void VisitIgnoredValue(const Expr *E) {8331EvaluateIgnoredValue(Info, E);8332}83338334/// Potentially visit a MemberExpr's base expression.8335void VisitIgnoredBaseExpression(const Expr *E) {8336// While MSVC doesn't evaluate the base expression, it does diagnose the8337// presence of side-effecting behavior.8338if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))8339return;8340VisitIgnoredValue(E);8341}8342};83438344} // namespace83458346//===----------------------------------------------------------------------===//8347// Common base class for lvalue and temporary evaluation.8348//===----------------------------------------------------------------------===//8349namespace {8350template<class Derived>8351class LValueExprEvaluatorBase8352: public ExprEvaluatorBase<Derived> {8353protected:8354LValue &Result;8355bool InvalidBaseOK;8356typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;8357typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;83588359bool Success(APValue::LValueBase B) {8360Result.set(B);8361return true;8362}83638364bool evaluatePointer(const Expr *E, LValue &Result) {8365return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);8366}83678368public:8369LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)8370: ExprEvaluatorBaseTy(Info), Result(Result),8371InvalidBaseOK(InvalidBaseOK) {}83728373bool Success(const APValue &V, const Expr *E) {8374Result.setFrom(this->Info.Ctx, V);8375return true;8376}83778378bool VisitMemberExpr(const MemberExpr *E) {8379// Handle non-static data members.8380QualType BaseTy;8381bool EvalOK;8382if (E->isArrow()) {8383EvalOK = evaluatePointer(E->getBase(), Result);8384BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();8385} else if (E->getBase()->isPRValue()) {8386assert(E->getBase()->getType()->isRecordType());8387EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);8388BaseTy = E->getBase()->getType();8389} else {8390EvalOK = this->Visit(E->getBase());8391BaseTy = E->getBase()->getType();8392}8393if (!EvalOK) {8394if (!InvalidBaseOK)8395return false;8396Result.setInvalid(E);8397return true;8398}83998400const ValueDecl *MD = E->getMemberDecl();8401if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {8402assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==8403FD->getParent()->getCanonicalDecl() && "record / field mismatch");8404(void)BaseTy;8405if (!HandleLValueMember(this->Info, E, Result, FD))8406return false;8407} else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {8408if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))8409return false;8410} else8411return this->Error(E);84128413if (MD->getType()->isReferenceType()) {8414APValue RefValue;8415if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,8416RefValue))8417return false;8418return Success(RefValue, E);8419}8420return true;8421}84228423bool VisitBinaryOperator(const BinaryOperator *E) {8424switch (E->getOpcode()) {8425default:8426return ExprEvaluatorBaseTy::VisitBinaryOperator(E);84278428case BO_PtrMemD:8429case BO_PtrMemI:8430return HandleMemberPointerAccess(this->Info, E, Result);8431}8432}84338434bool VisitCastExpr(const CastExpr *E) {8435switch (E->getCastKind()) {8436default:8437return ExprEvaluatorBaseTy::VisitCastExpr(E);84388439case CK_DerivedToBase:8440case CK_UncheckedDerivedToBase:8441if (!this->Visit(E->getSubExpr()))8442return false;84438444// Now figure out the necessary offset to add to the base LV to get from8445// the derived class to the base class.8446return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),8447Result);8448}8449}8450};8451}84528453//===----------------------------------------------------------------------===//8454// LValue Evaluation8455//8456// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),8457// function designators (in C), decl references to void objects (in C), and8458// temporaries (if building with -Wno-address-of-temporary).8459//8460// LValue evaluation produces values comprising a base expression of one of the8461// following types:8462// - Declarations8463// * VarDecl8464// * FunctionDecl8465// - Literals8466// * CompoundLiteralExpr in C (and in global scope in C++)8467// * StringLiteral8468// * PredefinedExpr8469// * ObjCStringLiteralExpr8470// * ObjCEncodeExpr8471// * AddrLabelExpr8472// * BlockExpr8473// * CallExpr for a MakeStringConstant builtin8474// - typeid(T) expressions, as TypeInfoLValues8475// - Locals and temporaries8476// * MaterializeTemporaryExpr8477// * Any Expr, with a CallIndex indicating the function in which the temporary8478// was evaluated, for cases where the MaterializeTemporaryExpr is missing8479// from the AST (FIXME).8480// * A MaterializeTemporaryExpr that has static storage duration, with no8481// CallIndex, for a lifetime-extended temporary.8482// * The ConstantExpr that is currently being evaluated during evaluation of an8483// immediate invocation.8484// plus an offset in bytes.8485//===----------------------------------------------------------------------===//8486namespace {8487class LValueExprEvaluator8488: public LValueExprEvaluatorBase<LValueExprEvaluator> {8489public:8490LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :8491LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}84928493bool VisitVarDecl(const Expr *E, const VarDecl *VD);8494bool VisitUnaryPreIncDec(const UnaryOperator *UO);84958496bool VisitCallExpr(const CallExpr *E);8497bool VisitDeclRefExpr(const DeclRefExpr *E);8498bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }8499bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);8500bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);8501bool VisitMemberExpr(const MemberExpr *E);8502bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }8503bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }8504bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);8505bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);8506bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);8507bool VisitUnaryDeref(const UnaryOperator *E);8508bool VisitUnaryReal(const UnaryOperator *E);8509bool VisitUnaryImag(const UnaryOperator *E);8510bool VisitUnaryPreInc(const UnaryOperator *UO) {8511return VisitUnaryPreIncDec(UO);8512}8513bool VisitUnaryPreDec(const UnaryOperator *UO) {8514return VisitUnaryPreIncDec(UO);8515}8516bool VisitBinAssign(const BinaryOperator *BO);8517bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);85188519bool VisitCastExpr(const CastExpr *E) {8520switch (E->getCastKind()) {8521default:8522return LValueExprEvaluatorBaseTy::VisitCastExpr(E);85238524case CK_LValueBitCast:8525this->CCEDiag(E, diag::note_constexpr_invalid_cast)8526<< 2 << Info.Ctx.getLangOpts().CPlusPlus;8527if (!Visit(E->getSubExpr()))8528return false;8529Result.Designator.setInvalid();8530return true;85318532case CK_BaseToDerived:8533if (!Visit(E->getSubExpr()))8534return false;8535return HandleBaseToDerivedCast(Info, E, Result);85368537case CK_Dynamic:8538if (!Visit(E->getSubExpr()))8539return false;8540return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);8541}8542}8543};8544} // end anonymous namespace85458546/// Get an lvalue to a field of a lambda's closure type.8547static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,8548const CXXMethodDecl *MD, const FieldDecl *FD,8549bool LValueToRValueConversion) {8550// Static lambda function call operators can't have captures. We already8551// diagnosed this, so bail out here.8552if (MD->isStatic()) {8553assert(Info.CurrentCall->This == nullptr &&8554"This should not be set for a static call operator");8555return false;8556}85578558// Start with 'Result' referring to the complete closure object...8559if (MD->isExplicitObjectMemberFunction()) {8560// Self may be passed by reference or by value.8561const ParmVarDecl *Self = MD->getParamDecl(0);8562if (Self->getType()->isReferenceType()) {8563APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);8564Result.setFrom(Info.Ctx, *RefValue);8565} else {8566const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);8567CallStackFrame *Frame =8568Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)8569.first;8570unsigned Version = Info.CurrentCall->Arguments.Version;8571Result.set({VD, Frame->Index, Version});8572}8573} else8574Result = *Info.CurrentCall->This;85758576// ... then update it to refer to the field of the closure object8577// that represents the capture.8578if (!HandleLValueMember(Info, E, Result, FD))8579return false;85808581// And if the field is of reference type (or if we captured '*this' by8582// reference), update 'Result' to refer to what8583// the field refers to.8584if (LValueToRValueConversion) {8585APValue RVal;8586if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))8587return false;8588Result.setFrom(Info.Ctx, RVal);8589}8590return true;8591}85928593/// Evaluate an expression as an lvalue. This can be legitimately called on8594/// expressions which are not glvalues, in three cases:8595/// * function designators in C, and8596/// * "extern void" objects8597/// * @selector() expressions in Objective-C8598static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,8599bool InvalidBaseOK) {8600assert(!E->isValueDependent());8601assert(E->isGLValue() || E->getType()->isFunctionType() ||8602E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));8603return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);8604}86058606bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {8607const NamedDecl *D = E->getDecl();8608if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,8609UnnamedGlobalConstantDecl>(D))8610return Success(cast<ValueDecl>(D));8611if (const VarDecl *VD = dyn_cast<VarDecl>(D))8612return VisitVarDecl(E, VD);8613if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))8614return Visit(BD->getBinding());8615return Error(E);8616}861786188619bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {86208621// If we are within a lambda's call operator, check whether the 'VD' referred8622// to within 'E' actually represents a lambda-capture that maps to a8623// data-member/field within the closure object, and if so, evaluate to the8624// field or what the field refers to.8625if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&8626isa<DeclRefExpr>(E) &&8627cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {8628// We don't always have a complete capture-map when checking or inferring if8629// the function call operator meets the requirements of a constexpr function8630// - but we don't need to evaluate the captures to determine constexprness8631// (dcl.constexpr C++17).8632if (Info.checkingPotentialConstantExpression())8633return false;86348635if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {8636const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);8637return HandleLambdaCapture(Info, E, Result, MD, FD,8638FD->getType()->isReferenceType());8639}8640}86418642CallStackFrame *Frame = nullptr;8643unsigned Version = 0;8644if (VD->hasLocalStorage()) {8645// Only if a local variable was declared in the function currently being8646// evaluated, do we expect to be able to find its value in the current8647// frame. (Otherwise it was likely declared in an enclosing context and8648// could either have a valid evaluatable value (for e.g. a constexpr8649// variable) or be ill-formed (and trigger an appropriate evaluation8650// diagnostic)).8651CallStackFrame *CurrFrame = Info.CurrentCall;8652if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {8653// Function parameters are stored in some caller's frame. (Usually the8654// immediate caller, but for an inherited constructor they may be more8655// distant.)8656if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {8657if (CurrFrame->Arguments) {8658VD = CurrFrame->Arguments.getOrigParam(PVD);8659Frame =8660Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;8661Version = CurrFrame->Arguments.Version;8662}8663} else {8664Frame = CurrFrame;8665Version = CurrFrame->getCurrentTemporaryVersion(VD);8666}8667}8668}86698670if (!VD->getType()->isReferenceType()) {8671if (Frame) {8672Result.set({VD, Frame->Index, Version});8673return true;8674}8675return Success(VD);8676}86778678if (!Info.getLangOpts().CPlusPlus11) {8679Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)8680<< VD << VD->getType();8681Info.Note(VD->getLocation(), diag::note_declared_at);8682}86838684APValue *V;8685if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))8686return false;8687if (!V->hasValue()) {8688// FIXME: Is it possible for V to be indeterminate here? If so, we should8689// adjust the diagnostic to say that.8690if (!Info.checkingPotentialConstantExpression())8691Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);8692return false;8693}8694return Success(*V, E);8695}86968697bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {8698if (!IsConstantEvaluatedBuiltinCall(E))8699return ExprEvaluatorBaseTy::VisitCallExpr(E);87008701switch (E->getBuiltinCallee()) {8702default:8703return false;8704case Builtin::BIas_const:8705case Builtin::BIforward:8706case Builtin::BIforward_like:8707case Builtin::BImove:8708case Builtin::BImove_if_noexcept:8709if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())8710return Visit(E->getArg(0));8711break;8712}87138714return ExprEvaluatorBaseTy::VisitCallExpr(E);8715}87168717bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(8718const MaterializeTemporaryExpr *E) {8719// Walk through the expression to find the materialized temporary itself.8720SmallVector<const Expr *, 2> CommaLHSs;8721SmallVector<SubobjectAdjustment, 2> Adjustments;8722const Expr *Inner =8723E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);87248725// If we passed any comma operators, evaluate their LHSs.8726for (const Expr *E : CommaLHSs)8727if (!EvaluateIgnoredValue(Info, E))8728return false;87298730// A materialized temporary with static storage duration can appear within the8731// result of a constant expression evaluation, so we need to preserve its8732// value for use outside this evaluation.8733APValue *Value;8734if (E->getStorageDuration() == SD_Static) {8735if (Info.EvalMode == EvalInfo::EM_ConstantFold)8736return false;8737// FIXME: What about SD_Thread?8738Value = E->getOrCreateValue(true);8739*Value = APValue();8740Result.set(E);8741} else {8742Value = &Info.CurrentCall->createTemporary(8743E, Inner->getType(),8744E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression8745: ScopeKind::Block,8746Result);8747}87488749QualType Type = Inner->getType();87508751// Materialize the temporary itself.8752if (!EvaluateInPlace(*Value, Info, Result, Inner)) {8753*Value = APValue();8754return false;8755}87568757// Adjust our lvalue to refer to the desired subobject.8758for (unsigned I = Adjustments.size(); I != 0; /**/) {8759--I;8760switch (Adjustments[I].Kind) {8761case SubobjectAdjustment::DerivedToBaseAdjustment:8762if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,8763Type, Result))8764return false;8765Type = Adjustments[I].DerivedToBase.BasePath->getType();8766break;87678768case SubobjectAdjustment::FieldAdjustment:8769if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))8770return false;8771Type = Adjustments[I].Field->getType();8772break;87738774case SubobjectAdjustment::MemberPointerAdjustment:8775if (!HandleMemberPointerAccess(this->Info, Type, Result,8776Adjustments[I].Ptr.RHS))8777return false;8778Type = Adjustments[I].Ptr.MPT->getPointeeType();8779break;8780}8781}87828783return true;8784}87858786bool8787LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {8788assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&8789"lvalue compound literal in c++?");8790// Defer visiting the literal until the lvalue-to-rvalue conversion. We can8791// only see this when folding in C, so there's no standard to follow here.8792return Success(E);8793}87948795bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {8796TypeInfoLValue TypeInfo;87978798if (!E->isPotentiallyEvaluated()) {8799if (E->isTypeOperand())8800TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());8801else8802TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());8803} else {8804if (!Info.Ctx.getLangOpts().CPlusPlus20) {8805Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)8806<< E->getExprOperand()->getType()8807<< E->getExprOperand()->getSourceRange();8808}88098810if (!Visit(E->getExprOperand()))8811return false;88128813std::optional<DynamicType> DynType =8814ComputeDynamicType(Info, E, Result, AK_TypeId);8815if (!DynType)8816return false;88178818TypeInfo =8819TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());8820}88218822return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));8823}88248825bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {8826return Success(E->getGuidDecl());8827}88288829bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {8830// Handle static data members.8831if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {8832VisitIgnoredBaseExpression(E->getBase());8833return VisitVarDecl(E, VD);8834}88358836// Handle static member functions.8837if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {8838if (MD->isStatic()) {8839VisitIgnoredBaseExpression(E->getBase());8840return Success(MD);8841}8842}88438844// Handle non-static data members.8845return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);8846}88478848bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {8849// FIXME: Deal with vectors as array subscript bases.8850if (E->getBase()->getType()->isVectorType() ||8851E->getBase()->getType()->isSveVLSBuiltinType())8852return Error(E);88538854APSInt Index;8855bool Success = true;88568857// C++17's rules require us to evaluate the LHS first, regardless of which8858// side is the base.8859for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {8860if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)8861: !EvaluateInteger(SubExpr, Index, Info)) {8862if (!Info.noteFailure())8863return false;8864Success = false;8865}8866}88678868return Success &&8869HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);8870}88718872bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {8873return evaluatePointer(E->getSubExpr(), Result);8874}88758876bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {8877if (!Visit(E->getSubExpr()))8878return false;8879// __real is a no-op on scalar lvalues.8880if (E->getSubExpr()->getType()->isAnyComplexType())8881HandleLValueComplexElement(Info, E, Result, E->getType(), false);8882return true;8883}88848885bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {8886assert(E->getSubExpr()->getType()->isAnyComplexType() &&8887"lvalue __imag__ on scalar?");8888if (!Visit(E->getSubExpr()))8889return false;8890HandleLValueComplexElement(Info, E, Result, E->getType(), true);8891return true;8892}88938894bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {8895if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())8896return Error(UO);88978898if (!this->Visit(UO->getSubExpr()))8899return false;89008901return handleIncDec(8902this->Info, UO, Result, UO->getSubExpr()->getType(),8903UO->isIncrementOp(), nullptr);8904}89058906bool LValueExprEvaluator::VisitCompoundAssignOperator(8907const CompoundAssignOperator *CAO) {8908if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())8909return Error(CAO);89108911bool Success = true;89128913// C++17 onwards require that we evaluate the RHS first.8914APValue RHS;8915if (!Evaluate(RHS, this->Info, CAO->getRHS())) {8916if (!Info.noteFailure())8917return false;8918Success = false;8919}89208921// The overall lvalue result is the result of evaluating the LHS.8922if (!this->Visit(CAO->getLHS()) || !Success)8923return false;89248925return handleCompoundAssignment(8926this->Info, CAO,8927Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),8928CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);8929}89308931bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {8932if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())8933return Error(E);89348935bool Success = true;89368937// C++17 onwards require that we evaluate the RHS first.8938APValue NewVal;8939if (!Evaluate(NewVal, this->Info, E->getRHS())) {8940if (!Info.noteFailure())8941return false;8942Success = false;8943}89448945if (!this->Visit(E->getLHS()) || !Success)8946return false;89478948if (Info.getLangOpts().CPlusPlus20 &&8949!MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))8950return false;89518952return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),8953NewVal);8954}89558956//===----------------------------------------------------------------------===//8957// Pointer Evaluation8958//===----------------------------------------------------------------------===//89598960/// Attempts to compute the number of bytes available at the pointer8961/// returned by a function with the alloc_size attribute. Returns true if we8962/// were successful. Places an unsigned number into `Result`.8963///8964/// This expects the given CallExpr to be a call to a function with an8965/// alloc_size attribute.8966static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,8967const CallExpr *Call,8968llvm::APInt &Result) {8969const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);89708971assert(AllocSize && AllocSize->getElemSizeParam().isValid());8972unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();8973unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());8974if (Call->getNumArgs() <= SizeArgNo)8975return false;89768977auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {8978Expr::EvalResult ExprResult;8979if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))8980return false;8981Into = ExprResult.Val.getInt();8982if (Into.isNegative() || !Into.isIntN(BitsInSizeT))8983return false;8984Into = Into.zext(BitsInSizeT);8985return true;8986};89878988APSInt SizeOfElem;8989if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))8990return false;89918992if (!AllocSize->getNumElemsParam().isValid()) {8993Result = std::move(SizeOfElem);8994return true;8995}89968997APSInt NumberOfElems;8998unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();8999if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))9000return false;90019002bool Overflow;9003llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);9004if (Overflow)9005return false;90069007Result = std::move(BytesAvailable);9008return true;9009}90109011/// Convenience function. LVal's base must be a call to an alloc_size9012/// function.9013static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,9014const LValue &LVal,9015llvm::APInt &Result) {9016assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&9017"Can't get the size of a non alloc_size function");9018const auto *Base = LVal.getLValueBase().get<const Expr *>();9019const CallExpr *CE = tryUnwrapAllocSizeCall(Base);9020return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);9021}90229023/// Attempts to evaluate the given LValueBase as the result of a call to9024/// a function with the alloc_size attribute. If it was possible to do so, this9025/// function will return true, make Result's Base point to said function call,9026/// and mark Result's Base as invalid.9027static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,9028LValue &Result) {9029if (Base.isNull())9030return false;90319032// Because we do no form of static analysis, we only support const variables.9033//9034// Additionally, we can't support parameters, nor can we support static9035// variables (in the latter case, use-before-assign isn't UB; in the former,9036// we have no clue what they'll be assigned to).9037const auto *VD =9038dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());9039if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())9040return false;90419042const Expr *Init = VD->getAnyInitializer();9043if (!Init || Init->getType().isNull())9044return false;90459046const Expr *E = Init->IgnoreParens();9047if (!tryUnwrapAllocSizeCall(E))9048return false;90499050// Store E instead of E unwrapped so that the type of the LValue's base is9051// what the user wanted.9052Result.setInvalid(E);90539054QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();9055Result.addUnsizedArray(Info, E, Pointee);9056return true;9057}90589059namespace {9060class PointerExprEvaluator9061: public ExprEvaluatorBase<PointerExprEvaluator> {9062LValue &Result;9063bool InvalidBaseOK;90649065bool Success(const Expr *E) {9066Result.set(E);9067return true;9068}90699070bool evaluateLValue(const Expr *E, LValue &Result) {9071return EvaluateLValue(E, Result, Info, InvalidBaseOK);9072}90739074bool evaluatePointer(const Expr *E, LValue &Result) {9075return EvaluatePointer(E, Result, Info, InvalidBaseOK);9076}90779078bool visitNonBuiltinCallExpr(const CallExpr *E);9079public:90809081PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)9082: ExprEvaluatorBaseTy(info), Result(Result),9083InvalidBaseOK(InvalidBaseOK) {}90849085bool Success(const APValue &V, const Expr *E) {9086Result.setFrom(Info.Ctx, V);9087return true;9088}9089bool ZeroInitialization(const Expr *E) {9090Result.setNull(Info.Ctx, E->getType());9091return true;9092}90939094bool VisitBinaryOperator(const BinaryOperator *E);9095bool VisitCastExpr(const CastExpr* E);9096bool VisitUnaryAddrOf(const UnaryOperator *E);9097bool VisitObjCStringLiteral(const ObjCStringLiteral *E)9098{ return Success(E); }9099bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {9100if (E->isExpressibleAsConstantInitializer())9101return Success(E);9102if (Info.noteFailure())9103EvaluateIgnoredValue(Info, E->getSubExpr());9104return Error(E);9105}9106bool VisitAddrLabelExpr(const AddrLabelExpr *E)9107{ return Success(E); }9108bool VisitCallExpr(const CallExpr *E);9109bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);9110bool VisitBlockExpr(const BlockExpr *E) {9111if (!E->getBlockDecl()->hasCaptures())9112return Success(E);9113return Error(E);9114}9115bool VisitCXXThisExpr(const CXXThisExpr *E) {9116auto DiagnoseInvalidUseOfThis = [&] {9117if (Info.getLangOpts().CPlusPlus11)9118Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();9119else9120Info.FFDiag(E);9121};91229123// Can't look at 'this' when checking a potential constant expression.9124if (Info.checkingPotentialConstantExpression())9125return false;91269127bool IsExplicitLambda =9128isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);9129if (!IsExplicitLambda) {9130if (!Info.CurrentCall->This) {9131DiagnoseInvalidUseOfThis();9132return false;9133}91349135Result = *Info.CurrentCall->This;9136}91379138if (isLambdaCallOperator(Info.CurrentCall->Callee)) {9139// Ensure we actually have captured 'this'. If something was wrong with9140// 'this' capture, the error would have been previously reported.9141// Otherwise we can be inside of a default initialization of an object9142// declared by lambda's body, so no need to return false.9143if (!Info.CurrentCall->LambdaThisCaptureField) {9144if (IsExplicitLambda && !Info.CurrentCall->This) {9145DiagnoseInvalidUseOfThis();9146return false;9147}91489149return true;9150}91519152const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);9153return HandleLambdaCapture(9154Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,9155Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());9156}9157return true;9158}91599160bool VisitCXXNewExpr(const CXXNewExpr *E);91619162bool VisitSourceLocExpr(const SourceLocExpr *E) {9163assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");9164APValue LValResult = E->EvaluateInContext(9165Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());9166Result.setFrom(Info.Ctx, LValResult);9167return true;9168}91699170bool VisitEmbedExpr(const EmbedExpr *E) {9171llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");9172return true;9173}91749175bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {9176std::string ResultStr = E->ComputeName(Info.Ctx);91779178QualType CharTy = Info.Ctx.CharTy.withConst();9179APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),9180ResultStr.size() + 1);9181QualType ArrayTy = Info.Ctx.getConstantArrayType(9182CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);91839184StringLiteral *SL =9185StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,9186/*Pascal*/ false, ArrayTy, E->getLocation());91879188evaluateLValue(SL, Result);9189Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));9190return true;9191}91929193// FIXME: Missing: @protocol, @selector9194};9195} // end anonymous namespace91969197static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,9198bool InvalidBaseOK) {9199assert(!E->isValueDependent());9200assert(E->isPRValue() && E->getType()->hasPointerRepresentation());9201return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);9202}92039204bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {9205if (E->getOpcode() != BO_Add &&9206E->getOpcode() != BO_Sub)9207return ExprEvaluatorBaseTy::VisitBinaryOperator(E);92089209const Expr *PExp = E->getLHS();9210const Expr *IExp = E->getRHS();9211if (IExp->getType()->isPointerType())9212std::swap(PExp, IExp);92139214bool EvalPtrOK = evaluatePointer(PExp, Result);9215if (!EvalPtrOK && !Info.noteFailure())9216return false;92179218llvm::APSInt Offset;9219if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)9220return false;92219222if (E->getOpcode() == BO_Sub)9223negateAsSigned(Offset);92249225QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();9226return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);9227}92289229bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {9230return evaluateLValue(E->getSubExpr(), Result);9231}92329233// Is the provided decl 'std::source_location::current'?9234static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {9235if (!FD)9236return false;9237const IdentifierInfo *FnII = FD->getIdentifier();9238if (!FnII || !FnII->isStr("current"))9239return false;92409241const auto *RD = dyn_cast<RecordDecl>(FD->getParent());9242if (!RD)9243return false;92449245const IdentifierInfo *ClassII = RD->getIdentifier();9246return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");9247}92489249bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {9250const Expr *SubExpr = E->getSubExpr();92519252switch (E->getCastKind()) {9253default:9254break;9255case CK_BitCast:9256case CK_CPointerToObjCPointerCast:9257case CK_BlockPointerToObjCPointerCast:9258case CK_AnyPointerToBlockPointerCast:9259case CK_AddressSpaceConversion:9260if (!Visit(SubExpr))9261return false;9262// Bitcasts to cv void* are static_casts, not reinterpret_casts, so are9263// permitted in constant expressions in C++11. Bitcasts from cv void* are9264// also static_casts, but we disallow them as a resolution to DR1312.9265if (!E->getType()->isVoidPointerType()) {9266// In some circumstances, we permit casting from void* to cv1 T*, when the9267// actual pointee object is actually a cv2 T.9268bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&9269!Result.IsNullPtr;9270bool VoidPtrCastMaybeOK =9271Result.IsNullPtr ||9272(HasValidResult &&9273Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),9274E->getType()->getPointeeType()));9275// 1. We'll allow it in std::allocator::allocate, and anything which that9276// calls.9277// 2. HACK 2022-03-28: Work around an issue with libstdc++'s9278// <source_location> header. Fixed in GCC 12 and later (2022-04-??).9279// We'll allow it in the body of std::source_location::current. GCC's9280// implementation had a parameter of type `void*`, and casts from9281// that back to `const __impl*` in its body.9282if (VoidPtrCastMaybeOK &&9283(Info.getStdAllocatorCaller("allocate") ||9284IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||9285Info.getLangOpts().CPlusPlus26)) {9286// Permitted.9287} else {9288if (SubExpr->getType()->isVoidPointerType() &&9289Info.getLangOpts().CPlusPlus) {9290if (HasValidResult)9291CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)9292<< SubExpr->getType() << Info.getLangOpts().CPlusPlus269293<< Result.Designator.getType(Info.Ctx).getCanonicalType()9294<< E->getType()->getPointeeType();9295else9296CCEDiag(E, diag::note_constexpr_invalid_cast)9297<< 3 << SubExpr->getType();9298} else9299CCEDiag(E, diag::note_constexpr_invalid_cast)9300<< 2 << Info.Ctx.getLangOpts().CPlusPlus;9301Result.Designator.setInvalid();9302}9303}9304if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)9305ZeroInitialization(E);9306return true;93079308case CK_DerivedToBase:9309case CK_UncheckedDerivedToBase:9310if (!evaluatePointer(E->getSubExpr(), Result))9311return false;9312if (!Result.Base && Result.Offset.isZero())9313return true;93149315// Now figure out the necessary offset to add to the base LV to get from9316// the derived class to the base class.9317return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->9318castAs<PointerType>()->getPointeeType(),9319Result);93209321case CK_BaseToDerived:9322if (!Visit(E->getSubExpr()))9323return false;9324if (!Result.Base && Result.Offset.isZero())9325return true;9326return HandleBaseToDerivedCast(Info, E, Result);93279328case CK_Dynamic:9329if (!Visit(E->getSubExpr()))9330return false;9331return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);93329333case CK_NullToPointer:9334VisitIgnoredValue(E->getSubExpr());9335return ZeroInitialization(E);93369337case CK_IntegralToPointer: {9338CCEDiag(E, diag::note_constexpr_invalid_cast)9339<< 2 << Info.Ctx.getLangOpts().CPlusPlus;93409341APValue Value;9342if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))9343break;93449345if (Value.isInt()) {9346unsigned Size = Info.Ctx.getTypeSize(E->getType());9347uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();9348Result.Base = (Expr*)nullptr;9349Result.InvalidBase = false;9350Result.Offset = CharUnits::fromQuantity(N);9351Result.Designator.setInvalid();9352Result.IsNullPtr = false;9353return true;9354} else {9355// In rare instances, the value isn't an lvalue.9356// For example, when the value is the difference between the addresses of9357// two labels. We reject that as a constant expression because we can't9358// compute a valid offset to convert into a pointer.9359if (!Value.isLValue())9360return false;93619362// Cast is of an lvalue, no need to change value.9363Result.setFrom(Info.Ctx, Value);9364return true;9365}9366}93679368case CK_ArrayToPointerDecay: {9369if (SubExpr->isGLValue()) {9370if (!evaluateLValue(SubExpr, Result))9371return false;9372} else {9373APValue &Value = Info.CurrentCall->createTemporary(9374SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);9375if (!EvaluateInPlace(Value, Info, Result, SubExpr))9376return false;9377}9378// The result is a pointer to the first element of the array.9379auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());9380if (auto *CAT = dyn_cast<ConstantArrayType>(AT))9381Result.addArray(Info, E, CAT);9382else9383Result.addUnsizedArray(Info, E, AT->getElementType());9384return true;9385}93869387case CK_FunctionToPointerDecay:9388return evaluateLValue(SubExpr, Result);93899390case CK_LValueToRValue: {9391LValue LVal;9392if (!evaluateLValue(E->getSubExpr(), LVal))9393return false;93949395APValue RVal;9396// Note, we use the subexpression's type in order to retain cv-qualifiers.9397if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),9398LVal, RVal))9399return InvalidBaseOK &&9400evaluateLValueAsAllocSize(Info, LVal.Base, Result);9401return Success(RVal, E);9402}9403}94049405return ExprEvaluatorBaseTy::VisitCastExpr(E);9406}94079408static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,9409UnaryExprOrTypeTrait ExprKind) {9410// C++ [expr.alignof]p3:9411// When alignof is applied to a reference type, the result is the9412// alignment of the referenced type.9413T = T.getNonReferenceType();94149415if (T.getQualifiers().hasUnaligned())9416return CharUnits::One();94179418const bool AlignOfReturnsPreferred =9419Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;94209421// __alignof is defined to return the preferred alignment.9422// Before 8, clang returned the preferred alignment for alignof and _Alignof9423// as well.9424if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)9425return Info.Ctx.toCharUnitsFromBits(9426Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));9427// alignof and _Alignof are defined to return the ABI alignment.9428else if (ExprKind == UETT_AlignOf)9429return Info.Ctx.getTypeAlignInChars(T.getTypePtr());9430else9431llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");9432}94339434static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,9435UnaryExprOrTypeTrait ExprKind) {9436E = E->IgnoreParens();94379438// The kinds of expressions that we have special-case logic here for9439// should be kept up to date with the special checks for those9440// expressions in Sema.94419442// alignof decl is always accepted, even if it doesn't make sense: we default9443// to 1 in those cases.9444if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))9445return Info.Ctx.getDeclAlign(DRE->getDecl(),9446/*RefAsPointee*/true);94479448if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))9449return Info.Ctx.getDeclAlign(ME->getMemberDecl(),9450/*RefAsPointee*/true);94519452return GetAlignOfType(Info, E->getType(), ExprKind);9453}94549455static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {9456if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())9457return Info.Ctx.getDeclAlign(VD);9458if (const auto *E = Value.Base.dyn_cast<const Expr *>())9459return GetAlignOfExpr(Info, E, UETT_AlignOf);9460return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);9461}94629463/// Evaluate the value of the alignment argument to __builtin_align_{up,down},9464/// __builtin_is_aligned and __builtin_assume_aligned.9465static bool getAlignmentArgument(const Expr *E, QualType ForType,9466EvalInfo &Info, APSInt &Alignment) {9467if (!EvaluateInteger(E, Alignment, Info))9468return false;9469if (Alignment < 0 || !Alignment.isPowerOf2()) {9470Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;9471return false;9472}9473unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);9474APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));9475if (APSInt::compareValues(Alignment, MaxValue) > 0) {9476Info.FFDiag(E, diag::note_constexpr_alignment_too_big)9477<< MaxValue << ForType << Alignment;9478return false;9479}9480// Ensure both alignment and source value have the same bit width so that we9481// don't assert when computing the resulting value.9482APSInt ExtAlignment =9483APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);9484assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&9485"Alignment should not be changed by ext/trunc");9486Alignment = ExtAlignment;9487assert(Alignment.getBitWidth() == SrcWidth);9488return true;9489}94909491// To be clear: this happily visits unsupported builtins. Better name welcomed.9492bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {9493if (ExprEvaluatorBaseTy::VisitCallExpr(E))9494return true;94959496if (!(InvalidBaseOK && getAllocSizeAttr(E)))9497return false;94989499Result.setInvalid(E);9500QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();9501Result.addUnsizedArray(Info, E, PointeeTy);9502return true;9503}95049505bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {9506if (!IsConstantEvaluatedBuiltinCall(E))9507return visitNonBuiltinCallExpr(E);9508return VisitBuiltinCallExpr(E, E->getBuiltinCallee());9509}95109511// Determine if T is a character type for which we guarantee that9512// sizeof(T) == 1.9513static bool isOneByteCharacterType(QualType T) {9514return T->isCharType() || T->isChar8Type();9515}95169517bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,9518unsigned BuiltinOp) {9519if (IsNoOpCall(E))9520return Success(E);95219522switch (BuiltinOp) {9523case Builtin::BIaddressof:9524case Builtin::BI__addressof:9525case Builtin::BI__builtin_addressof:9526return evaluateLValue(E->getArg(0), Result);9527case Builtin::BI__builtin_assume_aligned: {9528// We need to be very careful here because: if the pointer does not have the9529// asserted alignment, then the behavior is undefined, and undefined9530// behavior is non-constant.9531if (!evaluatePointer(E->getArg(0), Result))9532return false;95339534LValue OffsetResult(Result);9535APSInt Alignment;9536if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,9537Alignment))9538return false;9539CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());95409541if (E->getNumArgs() > 2) {9542APSInt Offset;9543if (!EvaluateInteger(E->getArg(2), Offset, Info))9544return false;95459546int64_t AdditionalOffset = -Offset.getZExtValue();9547OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);9548}95499550// If there is a base object, then it must have the correct alignment.9551if (OffsetResult.Base) {9552CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);95539554if (BaseAlignment < Align) {9555Result.Designator.setInvalid();9556// FIXME: Add support to Diagnostic for long / long long.9557CCEDiag(E->getArg(0),9558diag::note_constexpr_baa_insufficient_alignment) << 09559<< (unsigned)BaseAlignment.getQuantity()9560<< (unsigned)Align.getQuantity();9561return false;9562}9563}95649565// The offset must also have the correct alignment.9566if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {9567Result.Designator.setInvalid();95689569(OffsetResult.Base9570? CCEDiag(E->getArg(0),9571diag::note_constexpr_baa_insufficient_alignment) << 19572: CCEDiag(E->getArg(0),9573diag::note_constexpr_baa_value_insufficient_alignment))9574<< (int)OffsetResult.Offset.getQuantity()9575<< (unsigned)Align.getQuantity();9576return false;9577}95789579return true;9580}9581case Builtin::BI__builtin_align_up:9582case Builtin::BI__builtin_align_down: {9583if (!evaluatePointer(E->getArg(0), Result))9584return false;9585APSInt Alignment;9586if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,9587Alignment))9588return false;9589CharUnits BaseAlignment = getBaseAlignment(Info, Result);9590CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);9591// For align_up/align_down, we can return the same value if the alignment9592// is known to be greater or equal to the requested value.9593if (PtrAlign.getQuantity() >= Alignment)9594return true;95959596// The alignment could be greater than the minimum at run-time, so we cannot9597// infer much about the resulting pointer value. One case is possible:9598// For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we9599// can infer the correct index if the requested alignment is smaller than9600// the base alignment so we can perform the computation on the offset.9601if (BaseAlignment.getQuantity() >= Alignment) {9602assert(Alignment.getBitWidth() <= 64 &&9603"Cannot handle > 64-bit address-space");9604uint64_t Alignment64 = Alignment.getZExtValue();9605CharUnits NewOffset = CharUnits::fromQuantity(9606BuiltinOp == Builtin::BI__builtin_align_down9607? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)9608: llvm::alignTo(Result.Offset.getQuantity(), Alignment64));9609Result.adjustOffset(NewOffset - Result.Offset);9610// TODO: diagnose out-of-bounds values/only allow for arrays?9611return true;9612}9613// Otherwise, we cannot constant-evaluate the result.9614Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)9615<< Alignment;9616return false;9617}9618case Builtin::BI__builtin_operator_new:9619return HandleOperatorNewCall(Info, E, Result);9620case Builtin::BI__builtin_launder:9621return evaluatePointer(E->getArg(0), Result);9622case Builtin::BIstrchr:9623case Builtin::BIwcschr:9624case Builtin::BImemchr:9625case Builtin::BIwmemchr:9626if (Info.getLangOpts().CPlusPlus11)9627Info.CCEDiag(E, diag::note_constexpr_invalid_function)9628<< /*isConstexpr*/ 0 << /*isConstructor*/ 09629<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();9630else9631Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);9632[[fallthrough]];9633case Builtin::BI__builtin_strchr:9634case Builtin::BI__builtin_wcschr:9635case Builtin::BI__builtin_memchr:9636case Builtin::BI__builtin_char_memchr:9637case Builtin::BI__builtin_wmemchr: {9638if (!Visit(E->getArg(0)))9639return false;9640APSInt Desired;9641if (!EvaluateInteger(E->getArg(1), Desired, Info))9642return false;9643uint64_t MaxLength = uint64_t(-1);9644if (BuiltinOp != Builtin::BIstrchr &&9645BuiltinOp != Builtin::BIwcschr &&9646BuiltinOp != Builtin::BI__builtin_strchr &&9647BuiltinOp != Builtin::BI__builtin_wcschr) {9648APSInt N;9649if (!EvaluateInteger(E->getArg(2), N, Info))9650return false;9651MaxLength = N.getZExtValue();9652}9653// We cannot find the value if there are no candidates to match against.9654if (MaxLength == 0u)9655return ZeroInitialization(E);9656if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||9657Result.Designator.Invalid)9658return false;9659QualType CharTy = Result.Designator.getType(Info.Ctx);9660bool IsRawByte = BuiltinOp == Builtin::BImemchr ||9661BuiltinOp == Builtin::BI__builtin_memchr;9662assert(IsRawByte ||9663Info.Ctx.hasSameUnqualifiedType(9664CharTy, E->getArg(0)->getType()->getPointeeType()));9665// Pointers to const void may point to objects of incomplete type.9666if (IsRawByte && CharTy->isIncompleteType()) {9667Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;9668return false;9669}9670// Give up on byte-oriented matching against multibyte elements.9671// FIXME: We can compare the bytes in the correct order.9672if (IsRawByte && !isOneByteCharacterType(CharTy)) {9673Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)9674<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()9675<< CharTy;9676return false;9677}9678// Figure out what value we're actually looking for (after converting to9679// the corresponding unsigned type if necessary).9680uint64_t DesiredVal;9681bool StopAtNull = false;9682switch (BuiltinOp) {9683case Builtin::BIstrchr:9684case Builtin::BI__builtin_strchr:9685// strchr compares directly to the passed integer, and therefore9686// always fails if given an int that is not a char.9687if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,9688E->getArg(1)->getType(),9689Desired),9690Desired))9691return ZeroInitialization(E);9692StopAtNull = true;9693[[fallthrough]];9694case Builtin::BImemchr:9695case Builtin::BI__builtin_memchr:9696case Builtin::BI__builtin_char_memchr:9697// memchr compares by converting both sides to unsigned char. That's also9698// correct for strchr if we get this far (to cope with plain char being9699// unsigned in the strchr case).9700DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();9701break;97029703case Builtin::BIwcschr:9704case Builtin::BI__builtin_wcschr:9705StopAtNull = true;9706[[fallthrough]];9707case Builtin::BIwmemchr:9708case Builtin::BI__builtin_wmemchr:9709// wcschr and wmemchr are given a wchar_t to look for. Just use it.9710DesiredVal = Desired.getZExtValue();9711break;9712}97139714for (; MaxLength; --MaxLength) {9715APValue Char;9716if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||9717!Char.isInt())9718return false;9719if (Char.getInt().getZExtValue() == DesiredVal)9720return true;9721if (StopAtNull && !Char.getInt())9722break;9723if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))9724return false;9725}9726// Not found: return nullptr.9727return ZeroInitialization(E);9728}97299730case Builtin::BImemcpy:9731case Builtin::BImemmove:9732case Builtin::BIwmemcpy:9733case Builtin::BIwmemmove:9734if (Info.getLangOpts().CPlusPlus11)9735Info.CCEDiag(E, diag::note_constexpr_invalid_function)9736<< /*isConstexpr*/ 0 << /*isConstructor*/ 09737<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();9738else9739Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);9740[[fallthrough]];9741case Builtin::BI__builtin_memcpy:9742case Builtin::BI__builtin_memmove:9743case Builtin::BI__builtin_wmemcpy:9744case Builtin::BI__builtin_wmemmove: {9745bool WChar = BuiltinOp == Builtin::BIwmemcpy ||9746BuiltinOp == Builtin::BIwmemmove ||9747BuiltinOp == Builtin::BI__builtin_wmemcpy ||9748BuiltinOp == Builtin::BI__builtin_wmemmove;9749bool Move = BuiltinOp == Builtin::BImemmove ||9750BuiltinOp == Builtin::BIwmemmove ||9751BuiltinOp == Builtin::BI__builtin_memmove ||9752BuiltinOp == Builtin::BI__builtin_wmemmove;97539754// The result of mem* is the first argument.9755if (!Visit(E->getArg(0)))9756return false;9757LValue Dest = Result;97589759LValue Src;9760if (!EvaluatePointer(E->getArg(1), Src, Info))9761return false;97629763APSInt N;9764if (!EvaluateInteger(E->getArg(2), N, Info))9765return false;9766assert(!N.isSigned() && "memcpy and friends take an unsigned size");97679768// If the size is zero, we treat this as always being a valid no-op.9769// (Even if one of the src and dest pointers is null.)9770if (!N)9771return true;97729773// Otherwise, if either of the operands is null, we can't proceed. Don't9774// try to determine the type of the copied objects, because there aren't9775// any.9776if (!Src.Base || !Dest.Base) {9777APValue Val;9778(!Src.Base ? Src : Dest).moveInto(Val);9779Info.FFDiag(E, diag::note_constexpr_memcpy_null)9780<< Move << WChar << !!Src.Base9781<< Val.getAsString(Info.Ctx, E->getArg(0)->getType());9782return false;9783}9784if (Src.Designator.Invalid || Dest.Designator.Invalid)9785return false;97869787// We require that Src and Dest are both pointers to arrays of9788// trivially-copyable type. (For the wide version, the designator will be9789// invalid if the designated object is not a wchar_t.)9790QualType T = Dest.Designator.getType(Info.Ctx);9791QualType SrcT = Src.Designator.getType(Info.Ctx);9792if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {9793// FIXME: Consider using our bit_cast implementation to support this.9794Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;9795return false;9796}9797if (T->isIncompleteType()) {9798Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;9799return false;9800}9801if (!T.isTriviallyCopyableType(Info.Ctx)) {9802Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;9803return false;9804}98059806// Figure out how many T's we're copying.9807uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();9808if (TSize == 0)9809return false;9810if (!WChar) {9811uint64_t Remainder;9812llvm::APInt OrigN = N;9813llvm::APInt::udivrem(OrigN, TSize, N, Remainder);9814if (Remainder) {9815Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)9816<< Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)9817<< (unsigned)TSize;9818return false;9819}9820}98219822// Check that the copying will remain within the arrays, just so that we9823// can give a more meaningful diagnostic. This implicitly also checks that9824// N fits into 64 bits.9825uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;9826uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;9827if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {9828Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)9829<< Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T9830<< toString(N, 10, /*Signed*/false);9831return false;9832}9833uint64_t NElems = N.getZExtValue();9834uint64_t NBytes = NElems * TSize;98359836// Check for overlap.9837int Direction = 1;9838if (HasSameBase(Src, Dest)) {9839uint64_t SrcOffset = Src.getLValueOffset().getQuantity();9840uint64_t DestOffset = Dest.getLValueOffset().getQuantity();9841if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {9842// Dest is inside the source region.9843if (!Move) {9844Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;9845return false;9846}9847// For memmove and friends, copy backwards.9848if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||9849!HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))9850return false;9851Direction = -1;9852} else if (!Move && SrcOffset >= DestOffset &&9853SrcOffset - DestOffset < NBytes) {9854// Src is inside the destination region for memcpy: invalid.9855Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;9856return false;9857}9858}98599860while (true) {9861APValue Val;9862// FIXME: Set WantObjectRepresentation to true if we're copying a9863// char-like type?9864if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||9865!handleAssignment(Info, E, Dest, T, Val))9866return false;9867// Do not iterate past the last element; if we're copying backwards, that9868// might take us off the start of the array.9869if (--NElems == 0)9870return true;9871if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||9872!HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))9873return false;9874}9875}98769877default:9878return false;9879}9880}98819882static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,9883APValue &Result, const InitListExpr *ILE,9884QualType AllocType);9885static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,9886APValue &Result,9887const CXXConstructExpr *CCE,9888QualType AllocType);98899890bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {9891if (!Info.getLangOpts().CPlusPlus20)9892Info.CCEDiag(E, diag::note_constexpr_new);98939894// We cannot speculatively evaluate a delete expression.9895if (Info.SpeculativeEvaluationDepth)9896return false;98979898FunctionDecl *OperatorNew = E->getOperatorNew();98999900bool IsNothrow = false;9901bool IsPlacement = false;9902if (OperatorNew->isReservedGlobalPlacementOperator() &&9903Info.CurrentCall->isStdFunction() && !E->isArray()) {9904// FIXME Support array placement new.9905assert(E->getNumPlacementArgs() == 1);9906if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))9907return false;9908if (Result.Designator.Invalid)9909return false;9910IsPlacement = true;9911} else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {9912Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)9913<< isa<CXXMethodDecl>(OperatorNew) << OperatorNew;9914return false;9915} else if (E->getNumPlacementArgs()) {9916// The only new-placement list we support is of the form (std::nothrow).9917//9918// FIXME: There is no restriction on this, but it's not clear that any9919// other form makes any sense. We get here for cases such as:9920//9921// new (std::align_val_t{N}) X(int)9922//9923// (which should presumably be valid only if N is a multiple of9924// alignof(int), and in any case can't be deallocated unless N is9925// alignof(X) and X has new-extended alignment).9926if (E->getNumPlacementArgs() != 1 ||9927!E->getPlacementArg(0)->getType()->isNothrowT())9928return Error(E, diag::note_constexpr_new_placement);99299930LValue Nothrow;9931if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))9932return false;9933IsNothrow = true;9934}99359936const Expr *Init = E->getInitializer();9937const InitListExpr *ResizedArrayILE = nullptr;9938const CXXConstructExpr *ResizedArrayCCE = nullptr;9939bool ValueInit = false;99409941QualType AllocType = E->getAllocatedType();9942if (std::optional<const Expr *> ArraySize = E->getArraySize()) {9943const Expr *Stripped = *ArraySize;9944for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);9945Stripped = ICE->getSubExpr())9946if (ICE->getCastKind() != CK_NoOp &&9947ICE->getCastKind() != CK_IntegralCast)9948break;99499950llvm::APSInt ArrayBound;9951if (!EvaluateInteger(Stripped, ArrayBound, Info))9952return false;99539954// C++ [expr.new]p9:9955// The expression is erroneous if:9956// -- [...] its value before converting to size_t [or] applying the9957// second standard conversion sequence is less than zero9958if (ArrayBound.isSigned() && ArrayBound.isNegative()) {9959if (IsNothrow)9960return ZeroInitialization(E);99619962Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)9963<< ArrayBound << (*ArraySize)->getSourceRange();9964return false;9965}99669967// -- its value is such that the size of the allocated object would9968// exceed the implementation-defined limit9969if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),9970ConstantArrayType::getNumAddressingBits(9971Info.Ctx, AllocType, ArrayBound),9972ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {9973if (IsNothrow)9974return ZeroInitialization(E);9975return false;9976}99779978// -- the new-initializer is a braced-init-list and the number of9979// array elements for which initializers are provided [...]9980// exceeds the number of elements to initialize9981if (!Init) {9982// No initialization is performed.9983} else if (isa<CXXScalarValueInitExpr>(Init) ||9984isa<ImplicitValueInitExpr>(Init)) {9985ValueInit = true;9986} else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {9987ResizedArrayCCE = CCE;9988} else {9989auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());9990assert(CAT && "unexpected type for array initializer");99919992unsigned Bits =9993std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());9994llvm::APInt InitBound = CAT->getSize().zext(Bits);9995llvm::APInt AllocBound = ArrayBound.zext(Bits);9996if (InitBound.ugt(AllocBound)) {9997if (IsNothrow)9998return ZeroInitialization(E);999910000Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)10001<< toString(AllocBound, 10, /*Signed=*/false)10002<< toString(InitBound, 10, /*Signed=*/false)10003<< (*ArraySize)->getSourceRange();10004return false;10005}1000610007// If the sizes differ, we must have an initializer list, and we need10008// special handling for this case when we initialize.10009if (InitBound != AllocBound)10010ResizedArrayILE = cast<InitListExpr>(Init);10011}1001210013AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,10014ArraySizeModifier::Normal, 0);10015} else {10016assert(!AllocType->isArrayType() &&10017"array allocation with non-array new");10018}1001910020APValue *Val;10021if (IsPlacement) {10022AccessKinds AK = AK_Construct;10023struct FindObjectHandler {10024EvalInfo &Info;10025const Expr *E;10026QualType AllocType;10027const AccessKinds AccessKind;10028APValue *Value;1002910030typedef bool result_type;10031bool failed() { return false; }10032bool found(APValue &Subobj, QualType SubobjType) {10033// FIXME: Reject the cases where [basic.life]p8 would not permit the10034// old name of the object to be used to name the new object.10035if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {10036Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<10037SubobjType << AllocType;10038return false;10039}10040Value = &Subobj;10041return true;10042}10043bool found(APSInt &Value, QualType SubobjType) {10044Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);10045return false;10046}10047bool found(APFloat &Value, QualType SubobjType) {10048Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);10049return false;10050}10051} Handler = {Info, E, AllocType, AK, nullptr};1005210053CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);10054if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))10055return false;1005610057Val = Handler.Value;1005810059// [basic.life]p1:10060// The lifetime of an object o of type T ends when [...] the storage10061// which the object occupies is [...] reused by an object that is not10062// nested within o (6.6.2).10063*Val = APValue();10064} else {10065// Perform the allocation and obtain a pointer to the resulting object.10066Val = Info.createHeapAlloc(E, AllocType, Result);10067if (!Val)10068return false;10069}1007010071if (ValueInit) {10072ImplicitValueInitExpr VIE(AllocType);10073if (!EvaluateInPlace(*Val, Info, Result, &VIE))10074return false;10075} else if (ResizedArrayILE) {10076if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,10077AllocType))10078return false;10079} else if (ResizedArrayCCE) {10080if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,10081AllocType))10082return false;10083} else if (Init) {10084if (!EvaluateInPlace(*Val, Info, Result, Init))10085return false;10086} else if (!handleDefaultInitValue(AllocType, *Val)) {10087return false;10088}1008910090// Array new returns a pointer to the first element, not a pointer to the10091// array.10092if (auto *AT = AllocType->getAsArrayTypeUnsafe())10093Result.addArray(Info, E, cast<ConstantArrayType>(AT));1009410095return true;10096}10097//===----------------------------------------------------------------------===//10098// Member Pointer Evaluation10099//===----------------------------------------------------------------------===//1010010101namespace {10102class MemberPointerExprEvaluator10103: public ExprEvaluatorBase<MemberPointerExprEvaluator> {10104MemberPtr &Result;1010510106bool Success(const ValueDecl *D) {10107Result = MemberPtr(D);10108return true;10109}10110public:1011110112MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)10113: ExprEvaluatorBaseTy(Info), Result(Result) {}1011410115bool Success(const APValue &V, const Expr *E) {10116Result.setFrom(V);10117return true;10118}10119bool ZeroInitialization(const Expr *E) {10120return Success((const ValueDecl*)nullptr);10121}1012210123bool VisitCastExpr(const CastExpr *E);10124bool VisitUnaryAddrOf(const UnaryOperator *E);10125};10126} // end anonymous namespace1012710128static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,10129EvalInfo &Info) {10130assert(!E->isValueDependent());10131assert(E->isPRValue() && E->getType()->isMemberPointerType());10132return MemberPointerExprEvaluator(Info, Result).Visit(E);10133}1013410135bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {10136switch (E->getCastKind()) {10137default:10138return ExprEvaluatorBaseTy::VisitCastExpr(E);1013910140case CK_NullToMemberPointer:10141VisitIgnoredValue(E->getSubExpr());10142return ZeroInitialization(E);1014310144case CK_BaseToDerivedMemberPointer: {10145if (!Visit(E->getSubExpr()))10146return false;10147if (E->path_empty())10148return true;10149// Base-to-derived member pointer casts store the path in derived-to-base10150// order, so iterate backwards. The CXXBaseSpecifier also provides us with10151// the wrong end of the derived->base arc, so stagger the path by one class.10152typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;10153for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());10154PathI != PathE; ++PathI) {10155assert(!(*PathI)->isVirtual() && "memptr cast through vbase");10156const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();10157if (!Result.castToDerived(Derived))10158return Error(E);10159}10160const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();10161if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))10162return Error(E);10163return true;10164}1016510166case CK_DerivedToBaseMemberPointer:10167if (!Visit(E->getSubExpr()))10168return false;10169for (CastExpr::path_const_iterator PathI = E->path_begin(),10170PathE = E->path_end(); PathI != PathE; ++PathI) {10171assert(!(*PathI)->isVirtual() && "memptr cast through vbase");10172const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();10173if (!Result.castToBase(Base))10174return Error(E);10175}10176return true;10177}10178}1017910180bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {10181// C++11 [expr.unary.op]p3 has very strict rules on how the address of a10182// member can be formed.10183return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());10184}1018510186//===----------------------------------------------------------------------===//10187// Record Evaluation10188//===----------------------------------------------------------------------===//1018910190namespace {10191class RecordExprEvaluator10192: public ExprEvaluatorBase<RecordExprEvaluator> {10193const LValue &This;10194APValue &Result;10195public:1019610197RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)10198: ExprEvaluatorBaseTy(info), This(This), Result(Result) {}1019910200bool Success(const APValue &V, const Expr *E) {10201Result = V;10202return true;10203}10204bool ZeroInitialization(const Expr *E) {10205return ZeroInitialization(E, E->getType());10206}10207bool ZeroInitialization(const Expr *E, QualType T);1020810209bool VisitCallExpr(const CallExpr *E) {10210return handleCallExpr(E, Result, &This);10211}10212bool VisitCastExpr(const CastExpr *E);10213bool VisitInitListExpr(const InitListExpr *E);10214bool VisitCXXConstructExpr(const CXXConstructExpr *E) {10215return VisitCXXConstructExpr(E, E->getType());10216}10217bool VisitLambdaExpr(const LambdaExpr *E);10218bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);10219bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);10220bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);10221bool VisitBinCmp(const BinaryOperator *E);10222bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);10223bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,10224ArrayRef<Expr *> Args);10225};10226}1022710228/// Perform zero-initialization on an object of non-union class type.10229/// C++11 [dcl.init]p5:10230/// To zero-initialize an object or reference of type T means:10231/// [...]10232/// -- if T is a (possibly cv-qualified) non-union class type,10233/// each non-static data member and each base-class subobject is10234/// zero-initialized10235static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,10236const RecordDecl *RD,10237const LValue &This, APValue &Result) {10238assert(!RD->isUnion() && "Expected non-union class type");10239const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);10240Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,10241std::distance(RD->field_begin(), RD->field_end()));1024210243if (RD->isInvalidDecl()) return false;10244const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);1024510246if (CD) {10247unsigned Index = 0;10248for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),10249End = CD->bases_end(); I != End; ++I, ++Index) {10250const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();10251LValue Subobject = This;10252if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))10253return false;10254if (!HandleClassZeroInitialization(Info, E, Base, Subobject,10255Result.getStructBase(Index)))10256return false;10257}10258}1025910260for (const auto *I : RD->fields()) {10261// -- if T is a reference type, no initialization is performed.10262if (I->isUnnamedBitField() || I->getType()->isReferenceType())10263continue;1026410265LValue Subobject = This;10266if (!HandleLValueMember(Info, E, Subobject, I, &Layout))10267return false;1026810269ImplicitValueInitExpr VIE(I->getType());10270if (!EvaluateInPlace(10271Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))10272return false;10273}1027410275return true;10276}1027710278bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {10279const RecordDecl *RD = T->castAs<RecordType>()->getDecl();10280if (RD->isInvalidDecl()) return false;10281if (RD->isUnion()) {10282// C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the10283// object's first non-static named data member is zero-initialized10284RecordDecl::field_iterator I = RD->field_begin();10285while (I != RD->field_end() && (*I)->isUnnamedBitField())10286++I;10287if (I == RD->field_end()) {10288Result = APValue((const FieldDecl*)nullptr);10289return true;10290}1029110292LValue Subobject = This;10293if (!HandleLValueMember(Info, E, Subobject, *I))10294return false;10295Result = APValue(*I);10296ImplicitValueInitExpr VIE(I->getType());10297return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);10298}1029910300if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {10301Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;10302return false;10303}1030410305return HandleClassZeroInitialization(Info, E, RD, This, Result);10306}1030710308bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {10309switch (E->getCastKind()) {10310default:10311return ExprEvaluatorBaseTy::VisitCastExpr(E);1031210313case CK_ConstructorConversion:10314return Visit(E->getSubExpr());1031510316case CK_DerivedToBase:10317case CK_UncheckedDerivedToBase: {10318APValue DerivedObject;10319if (!Evaluate(DerivedObject, Info, E->getSubExpr()))10320return false;10321if (!DerivedObject.isStruct())10322return Error(E->getSubExpr());1032310324// Derived-to-base rvalue conversion: just slice off the derived part.10325APValue *Value = &DerivedObject;10326const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();10327for (CastExpr::path_const_iterator PathI = E->path_begin(),10328PathE = E->path_end(); PathI != PathE; ++PathI) {10329assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");10330const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();10331Value = &Value->getStructBase(getBaseIndex(RD, Base));10332RD = Base;10333}10334Result = *Value;10335return true;10336}10337}10338}1033910340bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {10341if (E->isTransparent())10342return Visit(E->getInit(0));10343return VisitCXXParenListOrInitListExpr(E, E->inits());10344}1034510346bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(10347const Expr *ExprToVisit, ArrayRef<Expr *> Args) {10348const RecordDecl *RD =10349ExprToVisit->getType()->castAs<RecordType>()->getDecl();10350if (RD->isInvalidDecl()) return false;10351const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);10352auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);1035310354EvalInfo::EvaluatingConstructorRAII EvalObj(10355Info,10356ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},10357CXXRD && CXXRD->getNumBases());1035810359if (RD->isUnion()) {10360const FieldDecl *Field;10361if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {10362Field = ILE->getInitializedFieldInUnion();10363} else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {10364Field = PLIE->getInitializedFieldInUnion();10365} else {10366llvm_unreachable(10367"Expression is neither an init list nor a C++ paren list");10368}1036910370Result = APValue(Field);10371if (!Field)10372return true;1037310374// If the initializer list for a union does not contain any elements, the10375// first element of the union is value-initialized.10376// FIXME: The element should be initialized from an initializer list.10377// Is this difference ever observable for initializer lists which10378// we don't build?10379ImplicitValueInitExpr VIE(Field->getType());10380const Expr *InitExpr = Args.empty() ? &VIE : Args[0];1038110382LValue Subobject = This;10383if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))10384return false;1038510386// Temporarily override This, in case there's a CXXDefaultInitExpr in here.10387ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,10388isa<CXXDefaultInitExpr>(InitExpr));1038910390if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {10391if (Field->isBitField())10392return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),10393Field);10394return true;10395}1039610397return false;10398}1039910400if (!Result.hasValue())10401Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,10402std::distance(RD->field_begin(), RD->field_end()));10403unsigned ElementNo = 0;10404bool Success = true;1040510406// Initialize base classes.10407if (CXXRD && CXXRD->getNumBases()) {10408for (const auto &Base : CXXRD->bases()) {10409assert(ElementNo < Args.size() && "missing init for base class");10410const Expr *Init = Args[ElementNo];1041110412LValue Subobject = This;10413if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))10414return false;1041510416APValue &FieldVal = Result.getStructBase(ElementNo);10417if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {10418if (!Info.noteFailure())10419return false;10420Success = false;10421}10422++ElementNo;10423}1042410425EvalObj.finishedConstructingBases();10426}1042710428// Initialize members.10429for (const auto *Field : RD->fields()) {10430// Anonymous bit-fields are not considered members of the class for10431// purposes of aggregate initialization.10432if (Field->isUnnamedBitField())10433continue;1043410435LValue Subobject = This;1043610437bool HaveInit = ElementNo < Args.size();1043810439// FIXME: Diagnostics here should point to the end of the initializer10440// list, not the start.10441if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,10442Subobject, Field, &Layout))10443return false;1044410445// Perform an implicit value-initialization for members beyond the end of10446// the initializer list.10447ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());10448const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;1044910450if (Field->getType()->isIncompleteArrayType()) {10451if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {10452if (!CAT->isZeroSize()) {10453// Bail out for now. This might sort of "work", but the rest of the10454// code isn't really prepared to handle it.10455Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);10456return false;10457}10458}10459}1046010461// Temporarily override This, in case there's a CXXDefaultInitExpr in here.10462ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,10463isa<CXXDefaultInitExpr>(Init));1046410465APValue &FieldVal = Result.getStructField(Field->getFieldIndex());10466if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||10467(Field->isBitField() && !truncateBitfieldValue(Info, Init,10468FieldVal, Field))) {10469if (!Info.noteFailure())10470return false;10471Success = false;10472}10473}1047410475EvalObj.finishedConstructingFields();1047610477return Success;10478}1047910480bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,10481QualType T) {10482// Note that E's type is not necessarily the type of our class here; we might10483// be initializing an array element instead.10484const CXXConstructorDecl *FD = E->getConstructor();10485if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;1048610487bool ZeroInit = E->requiresZeroInitialization();10488if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {10489// If we've already performed zero-initialization, we're already done.10490if (Result.hasValue())10491return true;1049210493if (ZeroInit)10494return ZeroInitialization(E, T);1049510496return handleDefaultInitValue(T, Result);10497}1049810499const FunctionDecl *Definition = nullptr;10500auto Body = FD->getBody(Definition);1050110502if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))10503return false;1050410505// Avoid materializing a temporary for an elidable copy/move constructor.10506if (E->isElidable() && !ZeroInit) {10507// FIXME: This only handles the simplest case, where the source object10508// is passed directly as the first argument to the constructor.10509// This should also handle stepping though implicit casts and10510// and conversion sequences which involve two steps, with a10511// conversion operator followed by a converting constructor.10512const Expr *SrcObj = E->getArg(0);10513assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));10514assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));10515if (const MaterializeTemporaryExpr *ME =10516dyn_cast<MaterializeTemporaryExpr>(SrcObj))10517return Visit(ME->getSubExpr());10518}1051910520if (ZeroInit && !ZeroInitialization(E, T))10521return false;1052210523auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());10524return HandleConstructorCall(E, This, Args,10525cast<CXXConstructorDecl>(Definition), Info,10526Result);10527}1052810529bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(10530const CXXInheritedCtorInitExpr *E) {10531if (!Info.CurrentCall) {10532assert(Info.checkingPotentialConstantExpression());10533return false;10534}1053510536const CXXConstructorDecl *FD = E->getConstructor();10537if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())10538return false;1053910540const FunctionDecl *Definition = nullptr;10541auto Body = FD->getBody(Definition);1054210543if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))10544return false;1054510546return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,10547cast<CXXConstructorDecl>(Definition), Info,10548Result);10549}1055010551bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(10552const CXXStdInitializerListExpr *E) {10553const ConstantArrayType *ArrayType =10554Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());1055510556LValue Array;10557if (!EvaluateLValue(E->getSubExpr(), Array, Info))10558return false;1055910560assert(ArrayType && "unexpected type for array initializer");1056110562// Get a pointer to the first element of the array.10563Array.addArray(Info, E, ArrayType);1056410565// FIXME: What if the initializer_list type has base classes, etc?10566Result = APValue(APValue::UninitStruct(), 0, 2);10567Array.moveInto(Result.getStructField(0));1056810569RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();10570RecordDecl::field_iterator Field = Record->field_begin();10571assert(Field != Record->field_end() &&10572Info.Ctx.hasSameType(Field->getType()->getPointeeType(),10573ArrayType->getElementType()) &&10574"Expected std::initializer_list first field to be const E *");10575++Field;10576assert(Field != Record->field_end() &&10577"Expected std::initializer_list to have two fields");1057810579if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {10580// Length.10581Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));10582} else {10583// End pointer.10584assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),10585ArrayType->getElementType()) &&10586"Expected std::initializer_list second field to be const E *");10587if (!HandleLValueArrayAdjustment(Info, E, Array,10588ArrayType->getElementType(),10589ArrayType->getZExtSize()))10590return false;10591Array.moveInto(Result.getStructField(1));10592}1059310594assert(++Field == Record->field_end() &&10595"Expected std::initializer_list to only have two fields");1059610597return true;10598}1059910600bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {10601const CXXRecordDecl *ClosureClass = E->getLambdaClass();10602if (ClosureClass->isInvalidDecl())10603return false;1060410605const size_t NumFields =10606std::distance(ClosureClass->field_begin(), ClosureClass->field_end());1060710608assert(NumFields == (size_t)std::distance(E->capture_init_begin(),10609E->capture_init_end()) &&10610"The number of lambda capture initializers should equal the number of "10611"fields within the closure type");1061210613Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);10614// Iterate through all the lambda's closure object's fields and initialize10615// them.10616auto *CaptureInitIt = E->capture_init_begin();10617bool Success = true;10618const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);10619for (const auto *Field : ClosureClass->fields()) {10620assert(CaptureInitIt != E->capture_init_end());10621// Get the initializer for this field10622Expr *const CurFieldInit = *CaptureInitIt++;1062310624// If there is no initializer, either this is a VLA or an error has10625// occurred.10626if (!CurFieldInit)10627return Error(E);1062810629LValue Subobject = This;1063010631if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))10632return false;1063310634APValue &FieldVal = Result.getStructField(Field->getFieldIndex());10635if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {10636if (!Info.keepEvaluatingAfterFailure())10637return false;10638Success = false;10639}10640}10641return Success;10642}1064310644static bool EvaluateRecord(const Expr *E, const LValue &This,10645APValue &Result, EvalInfo &Info) {10646assert(!E->isValueDependent());10647assert(E->isPRValue() && E->getType()->isRecordType() &&10648"can't evaluate expression as a record rvalue");10649return RecordExprEvaluator(Info, This, Result).Visit(E);10650}1065110652//===----------------------------------------------------------------------===//10653// Temporary Evaluation10654//10655// Temporaries are represented in the AST as rvalues, but generally behave like10656// lvalues. The full-object of which the temporary is a subobject is implicitly10657// materialized so that a reference can bind to it.10658//===----------------------------------------------------------------------===//10659namespace {10660class TemporaryExprEvaluator10661: public LValueExprEvaluatorBase<TemporaryExprEvaluator> {10662public:10663TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :10664LValueExprEvaluatorBaseTy(Info, Result, false) {}1066510666/// Visit an expression which constructs the value of this temporary.10667bool VisitConstructExpr(const Expr *E) {10668APValue &Value = Info.CurrentCall->createTemporary(10669E, E->getType(), ScopeKind::FullExpression, Result);10670return EvaluateInPlace(Value, Info, Result, E);10671}1067210673bool VisitCastExpr(const CastExpr *E) {10674switch (E->getCastKind()) {10675default:10676return LValueExprEvaluatorBaseTy::VisitCastExpr(E);1067710678case CK_ConstructorConversion:10679return VisitConstructExpr(E->getSubExpr());10680}10681}10682bool VisitInitListExpr(const InitListExpr *E) {10683return VisitConstructExpr(E);10684}10685bool VisitCXXConstructExpr(const CXXConstructExpr *E) {10686return VisitConstructExpr(E);10687}10688bool VisitCallExpr(const CallExpr *E) {10689return VisitConstructExpr(E);10690}10691bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {10692return VisitConstructExpr(E);10693}10694bool VisitLambdaExpr(const LambdaExpr *E) {10695return VisitConstructExpr(E);10696}10697};10698} // end anonymous namespace1069910700/// Evaluate an expression of record type as a temporary.10701static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {10702assert(!E->isValueDependent());10703assert(E->isPRValue() && E->getType()->isRecordType());10704return TemporaryExprEvaluator(Info, Result).Visit(E);10705}1070610707//===----------------------------------------------------------------------===//10708// Vector Evaluation10709//===----------------------------------------------------------------------===//1071010711namespace {10712class VectorExprEvaluator10713: public ExprEvaluatorBase<VectorExprEvaluator> {10714APValue &Result;10715public:1071610717VectorExprEvaluator(EvalInfo &info, APValue &Result)10718: ExprEvaluatorBaseTy(info), Result(Result) {}1071910720bool Success(ArrayRef<APValue> V, const Expr *E) {10721assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());10722// FIXME: remove this APValue copy.10723Result = APValue(V.data(), V.size());10724return true;10725}10726bool Success(const APValue &V, const Expr *E) {10727assert(V.isVector());10728Result = V;10729return true;10730}10731bool ZeroInitialization(const Expr *E);1073210733bool VisitUnaryReal(const UnaryOperator *E)10734{ return Visit(E->getSubExpr()); }10735bool VisitCastExpr(const CastExpr* E);10736bool VisitInitListExpr(const InitListExpr *E);10737bool VisitUnaryImag(const UnaryOperator *E);10738bool VisitBinaryOperator(const BinaryOperator *E);10739bool VisitUnaryOperator(const UnaryOperator *E);10740bool VisitConvertVectorExpr(const ConvertVectorExpr *E);10741bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);1074210743// FIXME: Missing: conditional operator (for GNU10744// conditional select), ExtVectorElementExpr10745};10746} // end anonymous namespace1074710748static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {10749assert(E->isPRValue() && E->getType()->isVectorType() &&10750"not a vector prvalue");10751return VectorExprEvaluator(Info, Result).Visit(E);10752}1075310754bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {10755const VectorType *VTy = E->getType()->castAs<VectorType>();10756unsigned NElts = VTy->getNumElements();1075710758const Expr *SE = E->getSubExpr();10759QualType SETy = SE->getType();1076010761switch (E->getCastKind()) {10762case CK_VectorSplat: {10763APValue Val = APValue();10764if (SETy->isIntegerType()) {10765APSInt IntResult;10766if (!EvaluateInteger(SE, IntResult, Info))10767return false;10768Val = APValue(std::move(IntResult));10769} else if (SETy->isRealFloatingType()) {10770APFloat FloatResult(0.0);10771if (!EvaluateFloat(SE, FloatResult, Info))10772return false;10773Val = APValue(std::move(FloatResult));10774} else {10775return Error(E);10776}1077710778// Splat and create vector APValue.10779SmallVector<APValue, 4> Elts(NElts, Val);10780return Success(Elts, E);10781}10782case CK_BitCast: {10783APValue SVal;10784if (!Evaluate(SVal, Info, SE))10785return false;1078610787if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {10788// Give up if the input isn't an int, float, or vector. For example, we10789// reject "(v4i16)(intptr_t)&a".10790Info.FFDiag(E, diag::note_constexpr_invalid_cast)10791<< 2 << Info.Ctx.getLangOpts().CPlusPlus;10792return false;10793}1079410795if (!handleRValueToRValueBitCast(Info, Result, SVal, E))10796return false;1079710798return true;10799}10800default:10801return ExprEvaluatorBaseTy::VisitCastExpr(E);10802}10803}1080410805bool10806VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {10807const VectorType *VT = E->getType()->castAs<VectorType>();10808unsigned NumInits = E->getNumInits();10809unsigned NumElements = VT->getNumElements();1081010811QualType EltTy = VT->getElementType();10812SmallVector<APValue, 4> Elements;1081310814// The number of initializers can be less than the number of10815// vector elements. For OpenCL, this can be due to nested vector10816// initialization. For GCC compatibility, missing trailing elements10817// should be initialized with zeroes.10818unsigned CountInits = 0, CountElts = 0;10819while (CountElts < NumElements) {10820// Handle nested vector initialization.10821if (CountInits < NumInits10822&& E->getInit(CountInits)->getType()->isVectorType()) {10823APValue v;10824if (!EvaluateVector(E->getInit(CountInits), v, Info))10825return Error(E);10826unsigned vlen = v.getVectorLength();10827for (unsigned j = 0; j < vlen; j++)10828Elements.push_back(v.getVectorElt(j));10829CountElts += vlen;10830} else if (EltTy->isIntegerType()) {10831llvm::APSInt sInt(32);10832if (CountInits < NumInits) {10833if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))10834return false;10835} else // trailing integer zero.10836sInt = Info.Ctx.MakeIntValue(0, EltTy);10837Elements.push_back(APValue(sInt));10838CountElts++;10839} else {10840llvm::APFloat f(0.0);10841if (CountInits < NumInits) {10842if (!EvaluateFloat(E->getInit(CountInits), f, Info))10843return false;10844} else // trailing float zero.10845f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));10846Elements.push_back(APValue(f));10847CountElts++;10848}10849CountInits++;10850}10851return Success(Elements, E);10852}1085310854bool10855VectorExprEvaluator::ZeroInitialization(const Expr *E) {10856const auto *VT = E->getType()->castAs<VectorType>();10857QualType EltTy = VT->getElementType();10858APValue ZeroElement;10859if (EltTy->isIntegerType())10860ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));10861else10862ZeroElement =10863APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));1086410865SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);10866return Success(Elements, E);10867}1086810869bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {10870VisitIgnoredValue(E->getSubExpr());10871return ZeroInitialization(E);10872}1087310874bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {10875BinaryOperatorKind Op = E->getOpcode();10876assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&10877"Operation not supported on vector types");1087810879if (Op == BO_Comma)10880return ExprEvaluatorBaseTy::VisitBinaryOperator(E);1088110882Expr *LHS = E->getLHS();10883Expr *RHS = E->getRHS();1088410885assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&10886"Must both be vector types");10887// Checking JUST the types are the same would be fine, except shifts don't10888// need to have their types be the same (since you always shift by an int).10889assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==10890E->getType()->castAs<VectorType>()->getNumElements() &&10891RHS->getType()->castAs<VectorType>()->getNumElements() ==10892E->getType()->castAs<VectorType>()->getNumElements() &&10893"All operands must be the same size.");1089410895APValue LHSValue;10896APValue RHSValue;10897bool LHSOK = Evaluate(LHSValue, Info, LHS);10898if (!LHSOK && !Info.noteFailure())10899return false;10900if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)10901return false;1090210903if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))10904return false;1090510906return Success(LHSValue, E);10907}1090810909static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,10910QualType ResultTy,10911UnaryOperatorKind Op,10912APValue Elt) {10913switch (Op) {10914case UO_Plus:10915// Nothing to do here.10916return Elt;10917case UO_Minus:10918if (Elt.getKind() == APValue::Int) {10919Elt.getInt().negate();10920} else {10921assert(Elt.getKind() == APValue::Float &&10922"Vector can only be int or float type");10923Elt.getFloat().changeSign();10924}10925return Elt;10926case UO_Not:10927// This is only valid for integral types anyway, so we don't have to handle10928// float here.10929assert(Elt.getKind() == APValue::Int &&10930"Vector operator ~ can only be int");10931Elt.getInt().flipAllBits();10932return Elt;10933case UO_LNot: {10934if (Elt.getKind() == APValue::Int) {10935Elt.getInt() = !Elt.getInt();10936// operator ! on vectors returns -1 for 'truth', so negate it.10937Elt.getInt().negate();10938return Elt;10939}10940assert(Elt.getKind() == APValue::Float &&10941"Vector can only be int or float type");10942// Float types result in an int of the same size, but -1 for true, or 0 for10943// false.10944APSInt EltResult{Ctx.getIntWidth(ResultTy),10945ResultTy->isUnsignedIntegerType()};10946if (Elt.getFloat().isZero())10947EltResult.setAllBits();10948else10949EltResult.clearAllBits();1095010951return APValue{EltResult};10952}10953default:10954// FIXME: Implement the rest of the unary operators.10955return std::nullopt;10956}10957}1095810959bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {10960Expr *SubExpr = E->getSubExpr();10961const auto *VD = SubExpr->getType()->castAs<VectorType>();10962// This result element type differs in the case of negating a floating point10963// vector, since the result type is the a vector of the equivilant sized10964// integer.10965const QualType ResultEltTy = VD->getElementType();10966UnaryOperatorKind Op = E->getOpcode();1096710968APValue SubExprValue;10969if (!Evaluate(SubExprValue, Info, SubExpr))10970return false;1097110972// FIXME: This vector evaluator someday needs to be changed to be LValue10973// aware/keep LValue information around, rather than dealing with just vector10974// types directly. Until then, we cannot handle cases where the operand to10975// these unary operators is an LValue. The only case I've been able to see10976// cause this is operator++ assigning to a member expression (only valid in10977// altivec compilations) in C mode, so this shouldn't limit us too much.10978if (SubExprValue.isLValue())10979return false;1098010981assert(SubExprValue.getVectorLength() == VD->getNumElements() &&10982"Vector length doesn't match type?");1098310984SmallVector<APValue, 4> ResultElements;10985for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {10986std::optional<APValue> Elt = handleVectorUnaryOperator(10987Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));10988if (!Elt)10989return false;10990ResultElements.push_back(*Elt);10991}10992return Success(APValue(ResultElements.data(), ResultElements.size()), E);10993}1099410995static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,10996const Expr *E, QualType SourceTy,10997QualType DestTy, APValue const &Original,10998APValue &Result) {10999if (SourceTy->isIntegerType()) {11000if (DestTy->isRealFloatingType()) {11001Result = APValue(APFloat(0.0));11002return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),11003DestTy, Result.getFloat());11004}11005if (DestTy->isIntegerType()) {11006Result = APValue(11007HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));11008return true;11009}11010} else if (SourceTy->isRealFloatingType()) {11011if (DestTy->isRealFloatingType()) {11012Result = Original;11013return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,11014Result.getFloat());11015}11016if (DestTy->isIntegerType()) {11017Result = APValue(APSInt());11018return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),11019DestTy, Result.getInt());11020}11021}1102211023Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)11024<< SourceTy << DestTy;11025return false;11026}1102711028bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {11029APValue Source;11030QualType SourceVecType = E->getSrcExpr()->getType();11031if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))11032return false;1103311034QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();11035QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();1103611037const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());1103811039auto SourceLen = Source.getVectorLength();11040SmallVector<APValue, 4> ResultElements;11041ResultElements.reserve(SourceLen);11042for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {11043APValue Elt;11044if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,11045Source.getVectorElt(EltNum), Elt))11046return false;11047ResultElements.push_back(std::move(Elt));11048}1104911050return Success(APValue(ResultElements.data(), ResultElements.size()), E);11051}1105211053static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,11054QualType ElemType, APValue const &VecVal1,11055APValue const &VecVal2, unsigned EltNum,11056APValue &Result) {11057unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();11058unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();1105911060APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);11061int64_t index = IndexVal.getExtValue();11062// The spec says that -1 should be treated as undef for optimizations,11063// but in constexpr we'd have to produce an APValue::Indeterminate,11064// which is prohibited from being a top-level constant value. Emit a11065// diagnostic instead.11066if (index == -1) {11067Info.FFDiag(11068E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)11069<< EltNum;11070return false;11071}1107211073if (index < 0 ||11074index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)11075llvm_unreachable("Out of bounds shuffle index");1107611077if (index >= TotalElementsInInputVector1)11078Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);11079else11080Result = VecVal1.getVectorElt(index);11081return true;11082}1108311084bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {11085APValue VecVal1;11086const Expr *Vec1 = E->getExpr(0);11087if (!EvaluateAsRValue(Info, Vec1, VecVal1))11088return false;11089APValue VecVal2;11090const Expr *Vec2 = E->getExpr(1);11091if (!EvaluateAsRValue(Info, Vec2, VecVal2))11092return false;1109311094VectorType const *DestVecTy = E->getType()->castAs<VectorType>();11095QualType DestElTy = DestVecTy->getElementType();1109611097auto TotalElementsInOutputVector = DestVecTy->getNumElements();1109811099SmallVector<APValue, 4> ResultElements;11100ResultElements.reserve(TotalElementsInOutputVector);11101for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {11102APValue Elt;11103if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))11104return false;11105ResultElements.push_back(std::move(Elt));11106}1110711108return Success(APValue(ResultElements.data(), ResultElements.size()), E);11109}1111011111//===----------------------------------------------------------------------===//11112// Array Evaluation11113//===----------------------------------------------------------------------===//1111411115namespace {11116class ArrayExprEvaluator11117: public ExprEvaluatorBase<ArrayExprEvaluator> {11118const LValue &This;11119APValue &Result;11120public:1112111122ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)11123: ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}1112411125bool Success(const APValue &V, const Expr *E) {11126assert(V.isArray() && "expected array");11127Result = V;11128return true;11129}1113011131bool ZeroInitialization(const Expr *E) {11132const ConstantArrayType *CAT =11133Info.Ctx.getAsConstantArrayType(E->getType());11134if (!CAT) {11135if (E->getType()->isIncompleteArrayType()) {11136// We can be asked to zero-initialize a flexible array member; this11137// is represented as an ImplicitValueInitExpr of incomplete array11138// type. In this case, the array has zero elements.11139Result = APValue(APValue::UninitArray(), 0, 0);11140return true;11141}11142// FIXME: We could handle VLAs here.11143return Error(E);11144}1114511146Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());11147if (!Result.hasArrayFiller())11148return true;1114911150// Zero-initialize all elements.11151LValue Subobject = This;11152Subobject.addArray(Info, E, CAT);11153ImplicitValueInitExpr VIE(CAT->getElementType());11154return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);11155}1115611157bool VisitCallExpr(const CallExpr *E) {11158return handleCallExpr(E, Result, &This);11159}11160bool VisitInitListExpr(const InitListExpr *E,11161QualType AllocType = QualType());11162bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);11163bool VisitCXXConstructExpr(const CXXConstructExpr *E);11164bool VisitCXXConstructExpr(const CXXConstructExpr *E,11165const LValue &Subobject,11166APValue *Value, QualType Type);11167bool VisitStringLiteral(const StringLiteral *E,11168QualType AllocType = QualType()) {11169expandStringLiteral(Info, E, Result, AllocType);11170return true;11171}11172bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);11173bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,11174ArrayRef<Expr *> Args,11175const Expr *ArrayFiller,11176QualType AllocType = QualType());11177};11178} // end anonymous namespace1117911180static bool EvaluateArray(const Expr *E, const LValue &This,11181APValue &Result, EvalInfo &Info) {11182assert(!E->isValueDependent());11183assert(E->isPRValue() && E->getType()->isArrayType() &&11184"not an array prvalue");11185return ArrayExprEvaluator(Info, This, Result).Visit(E);11186}1118711188static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,11189APValue &Result, const InitListExpr *ILE,11190QualType AllocType) {11191assert(!ILE->isValueDependent());11192assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&11193"not an array prvalue");11194return ArrayExprEvaluator(Info, This, Result)11195.VisitInitListExpr(ILE, AllocType);11196}1119711198static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,11199APValue &Result,11200const CXXConstructExpr *CCE,11201QualType AllocType) {11202assert(!CCE->isValueDependent());11203assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&11204"not an array prvalue");11205return ArrayExprEvaluator(Info, This, Result)11206.VisitCXXConstructExpr(CCE, This, &Result, AllocType);11207}1120811209// Return true iff the given array filler may depend on the element index.11210static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {11211// For now, just allow non-class value-initialization and initialization11212// lists comprised of them.11213if (isa<ImplicitValueInitExpr>(FillerExpr))11214return false;11215if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {11216for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {11217if (MaybeElementDependentArrayFiller(ILE->getInit(I)))11218return true;11219}1122011221if (ILE->hasArrayFiller() &&11222MaybeElementDependentArrayFiller(ILE->getArrayFiller()))11223return true;1122411225return false;11226}11227return true;11228}1122911230bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,11231QualType AllocType) {11232const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(11233AllocType.isNull() ? E->getType() : AllocType);11234if (!CAT)11235return Error(E);1123611237// C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]11238// an appropriately-typed string literal enclosed in braces.11239if (E->isStringLiteralInit()) {11240auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());11241// FIXME: Support ObjCEncodeExpr here once we support it in11242// ArrayExprEvaluator generally.11243if (!SL)11244return Error(E);11245return VisitStringLiteral(SL, AllocType);11246}11247// Any other transparent list init will need proper handling of the11248// AllocType; we can't just recurse to the inner initializer.11249assert(!E->isTransparent() &&11250"transparent array list initialization is not string literal init?");1125111252return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),11253AllocType);11254}1125511256bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(11257const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,11258QualType AllocType) {11259const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(11260AllocType.isNull() ? ExprToVisit->getType() : AllocType);1126111262bool Success = true;1126311264assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&11265"zero-initialized array shouldn't have any initialized elts");11266APValue Filler;11267if (Result.isArray() && Result.hasArrayFiller())11268Filler = Result.getArrayFiller();1126911270unsigned NumEltsToInit = Args.size();11271unsigned NumElts = CAT->getZExtSize();1127211273// If the initializer might depend on the array index, run it for each11274// array element.11275if (NumEltsToInit != NumElts &&11276MaybeElementDependentArrayFiller(ArrayFiller)) {11277NumEltsToInit = NumElts;11278} else {11279for (auto *Init : Args) {11280if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))11281NumEltsToInit += EmbedS->getDataElementCount() - 1;11282}11283if (NumEltsToInit > NumElts)11284NumEltsToInit = NumElts;11285}1128611287LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "11288<< NumEltsToInit << ".\n");1128911290Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);1129111292// If the array was previously zero-initialized, preserve the11293// zero-initialized values.11294if (Filler.hasValue()) {11295for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)11296Result.getArrayInitializedElt(I) = Filler;11297if (Result.hasArrayFiller())11298Result.getArrayFiller() = Filler;11299}1130011301LValue Subobject = This;11302Subobject.addArray(Info, ExprToVisit, CAT);11303auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {11304if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,11305Subobject, Init) ||11306!HandleLValueArrayAdjustment(Info, Init, Subobject,11307CAT->getElementType(), 1)) {11308if (!Info.noteFailure())11309return false;11310Success = false;11311}11312return true;11313};11314unsigned ArrayIndex = 0;11315QualType DestTy = CAT->getElementType();11316APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());11317for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {11318const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;11319if (ArrayIndex >= NumEltsToInit)11320break;11321if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {11322StringLiteral *SL = EmbedS->getDataStringLiteral();11323for (unsigned I = EmbedS->getStartingElementPos(),11324N = EmbedS->getDataElementCount();11325I != EmbedS->getStartingElementPos() + N; ++I) {11326Value = SL->getCodeUnit(I);11327if (DestTy->isIntegerType()) {11328Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);11329} else {11330assert(DestTy->isFloatingType() && "unexpected type");11331const FPOptions FPO =11332Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());11333APFloat FValue(0.0);11334if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,11335DestTy, FValue))11336return false;11337Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);11338}11339ArrayIndex++;11340}11341} else {11342if (!Eval(Init, ArrayIndex))11343return false;11344++ArrayIndex;11345}11346}1134711348if (!Result.hasArrayFiller())11349return Success;1135011351// If we get here, we have a trivial filler, which we can just evaluate11352// once and splat over the rest of the array elements.11353assert(ArrayFiller && "no array filler for incomplete init list");11354return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,11355ArrayFiller) &&11356Success;11357}1135811359bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {11360LValue CommonLV;11361if (E->getCommonExpr() &&11362!Evaluate(Info.CurrentCall->createTemporary(11363E->getCommonExpr(),11364getStorageType(Info.Ctx, E->getCommonExpr()),11365ScopeKind::FullExpression, CommonLV),11366Info, E->getCommonExpr()->getSourceExpr()))11367return false;1136811369auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());1137011371uint64_t Elements = CAT->getZExtSize();11372Result = APValue(APValue::UninitArray(), Elements, Elements);1137311374LValue Subobject = This;11375Subobject.addArray(Info, E, CAT);1137611377bool Success = true;11378for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {11379// C++ [class.temporary]/511380// There are four contexts in which temporaries are destroyed at a different11381// point than the end of the full-expression. [...] The second context is11382// when a copy constructor is called to copy an element of an array while11383// the entire array is copied [...]. In either case, if the constructor has11384// one or more default arguments, the destruction of every temporary created11385// in a default argument is sequenced before the construction of the next11386// array element, if any.11387FullExpressionRAII Scope(Info);1138811389if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),11390Info, Subobject, E->getSubExpr()) ||11391!HandleLValueArrayAdjustment(Info, E, Subobject,11392CAT->getElementType(), 1)) {11393if (!Info.noteFailure())11394return false;11395Success = false;11396}1139711398// Make sure we run the destructors too.11399Scope.destroy();11400}1140111402return Success;11403}1140411405bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {11406return VisitCXXConstructExpr(E, This, &Result, E->getType());11407}1140811409bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,11410const LValue &Subobject,11411APValue *Value,11412QualType Type) {11413bool HadZeroInit = Value->hasValue();1141411415if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {11416unsigned FinalSize = CAT->getZExtSize();1141711418// Preserve the array filler if we had prior zero-initialization.11419APValue Filler =11420HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()11421: APValue();1142211423*Value = APValue(APValue::UninitArray(), 0, FinalSize);11424if (FinalSize == 0)11425return true;1142611427bool HasTrivialConstructor = CheckTrivialDefaultConstructor(11428Info, E->getExprLoc(), E->getConstructor(),11429E->requiresZeroInitialization());11430LValue ArrayElt = Subobject;11431ArrayElt.addArray(Info, E, CAT);11432// We do the whole initialization in two passes, first for just one element,11433// then for the whole array. It's possible we may find out we can't do const11434// init in the first pass, in which case we avoid allocating a potentially11435// large array. We don't do more passes because expanding array requires11436// copying the data, which is wasteful.11437for (const unsigned N : {1u, FinalSize}) {11438unsigned OldElts = Value->getArrayInitializedElts();11439if (OldElts == N)11440break;1144111442// Expand the array to appropriate size.11443APValue NewValue(APValue::UninitArray(), N, FinalSize);11444for (unsigned I = 0; I < OldElts; ++I)11445NewValue.getArrayInitializedElt(I).swap(11446Value->getArrayInitializedElt(I));11447Value->swap(NewValue);1144811449if (HadZeroInit)11450for (unsigned I = OldElts; I < N; ++I)11451Value->getArrayInitializedElt(I) = Filler;1145211453if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {11454// If we have a trivial constructor, only evaluate it once and copy11455// the result into all the array elements.11456APValue &FirstResult = Value->getArrayInitializedElt(0);11457for (unsigned I = OldElts; I < FinalSize; ++I)11458Value->getArrayInitializedElt(I) = FirstResult;11459} else {11460for (unsigned I = OldElts; I < N; ++I) {11461if (!VisitCXXConstructExpr(E, ArrayElt,11462&Value->getArrayInitializedElt(I),11463CAT->getElementType()) ||11464!HandleLValueArrayAdjustment(Info, E, ArrayElt,11465CAT->getElementType(), 1))11466return false;11467// When checking for const initilization any diagnostic is considered11468// an error.11469if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&11470!Info.keepEvaluatingAfterFailure())11471return false;11472}11473}11474}1147511476return true;11477}1147811479if (!Type->isRecordType())11480return Error(E);1148111482return RecordExprEvaluator(Info, Subobject, *Value)11483.VisitCXXConstructExpr(E, Type);11484}1148511486bool ArrayExprEvaluator::VisitCXXParenListInitExpr(11487const CXXParenListInitExpr *E) {11488assert(E->getType()->isConstantArrayType() &&11489"Expression result is not a constant array type");1149011491return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),11492E->getArrayFiller());11493}1149411495//===----------------------------------------------------------------------===//11496// Integer Evaluation11497//11498// As a GNU extension, we support casting pointers to sufficiently-wide integer11499// types and back in constant folding. Integer values are thus represented11500// either as an integer-valued APValue, or as an lvalue-valued APValue.11501//===----------------------------------------------------------------------===//1150211503namespace {11504class IntExprEvaluator11505: public ExprEvaluatorBase<IntExprEvaluator> {11506APValue &Result;11507public:11508IntExprEvaluator(EvalInfo &info, APValue &result)11509: ExprEvaluatorBaseTy(info), Result(result) {}1151011511bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {11512assert(E->getType()->isIntegralOrEnumerationType() &&11513"Invalid evaluation result.");11514assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&11515"Invalid evaluation result.");11516assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&11517"Invalid evaluation result.");11518Result = APValue(SI);11519return true;11520}11521bool Success(const llvm::APSInt &SI, const Expr *E) {11522return Success(SI, E, Result);11523}1152411525bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {11526assert(E->getType()->isIntegralOrEnumerationType() &&11527"Invalid evaluation result.");11528assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&11529"Invalid evaluation result.");11530Result = APValue(APSInt(I));11531Result.getInt().setIsUnsigned(11532E->getType()->isUnsignedIntegerOrEnumerationType());11533return true;11534}11535bool Success(const llvm::APInt &I, const Expr *E) {11536return Success(I, E, Result);11537}1153811539bool Success(uint64_t Value, const Expr *E, APValue &Result) {11540assert(E->getType()->isIntegralOrEnumerationType() &&11541"Invalid evaluation result.");11542Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));11543return true;11544}11545bool Success(uint64_t Value, const Expr *E) {11546return Success(Value, E, Result);11547}1154811549bool Success(CharUnits Size, const Expr *E) {11550return Success(Size.getQuantity(), E);11551}1155211553bool Success(const APValue &V, const Expr *E) {11554if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {11555Result = V;11556return true;11557}11558return Success(V.getInt(), E);11559}1156011561bool ZeroInitialization(const Expr *E) { return Success(0, E); }1156211563//===--------------------------------------------------------------------===//11564// Visitor Methods11565//===--------------------------------------------------------------------===//1156611567bool VisitIntegerLiteral(const IntegerLiteral *E) {11568return Success(E->getValue(), E);11569}11570bool VisitCharacterLiteral(const CharacterLiteral *E) {11571return Success(E->getValue(), E);11572}1157311574bool CheckReferencedDecl(const Expr *E, const Decl *D);11575bool VisitDeclRefExpr(const DeclRefExpr *E) {11576if (CheckReferencedDecl(E, E->getDecl()))11577return true;1157811579return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);11580}11581bool VisitMemberExpr(const MemberExpr *E) {11582if (CheckReferencedDecl(E, E->getMemberDecl())) {11583VisitIgnoredBaseExpression(E->getBase());11584return true;11585}1158611587return ExprEvaluatorBaseTy::VisitMemberExpr(E);11588}1158911590bool VisitCallExpr(const CallExpr *E);11591bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);11592bool VisitBinaryOperator(const BinaryOperator *E);11593bool VisitOffsetOfExpr(const OffsetOfExpr *E);11594bool VisitUnaryOperator(const UnaryOperator *E);1159511596bool VisitCastExpr(const CastExpr* E);11597bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);1159811599bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {11600return Success(E->getValue(), E);11601}1160211603bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {11604return Success(E->getValue(), E);11605}1160611607bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {11608if (Info.ArrayInitIndex == uint64_t(-1)) {11609// We were asked to evaluate this subexpression independent of the11610// enclosing ArrayInitLoopExpr. We can't do that.11611Info.FFDiag(E);11612return false;11613}11614return Success(Info.ArrayInitIndex, E);11615}1161611617// Note, GNU defines __null as an integer, not a pointer.11618bool VisitGNUNullExpr(const GNUNullExpr *E) {11619return ZeroInitialization(E);11620}1162111622bool VisitTypeTraitExpr(const TypeTraitExpr *E) {11623return Success(E->getValue(), E);11624}1162511626bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {11627return Success(E->getValue(), E);11628}1162911630bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {11631return Success(E->getValue(), E);11632}1163311634bool VisitUnaryReal(const UnaryOperator *E);11635bool VisitUnaryImag(const UnaryOperator *E);1163611637bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);11638bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);11639bool VisitSourceLocExpr(const SourceLocExpr *E);11640bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);11641bool VisitRequiresExpr(const RequiresExpr *E);11642// FIXME: Missing: array subscript of vector, member of vector11643};1164411645class FixedPointExprEvaluator11646: public ExprEvaluatorBase<FixedPointExprEvaluator> {11647APValue &Result;1164811649public:11650FixedPointExprEvaluator(EvalInfo &info, APValue &result)11651: ExprEvaluatorBaseTy(info), Result(result) {}1165211653bool Success(const llvm::APInt &I, const Expr *E) {11654return Success(11655APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);11656}1165711658bool Success(uint64_t Value, const Expr *E) {11659return Success(11660APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);11661}1166211663bool Success(const APValue &V, const Expr *E) {11664return Success(V.getFixedPoint(), E);11665}1166611667bool Success(const APFixedPoint &V, const Expr *E) {11668assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");11669assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&11670"Invalid evaluation result.");11671Result = APValue(V);11672return true;11673}1167411675bool ZeroInitialization(const Expr *E) {11676return Success(0, E);11677}1167811679//===--------------------------------------------------------------------===//11680// Visitor Methods11681//===--------------------------------------------------------------------===//1168211683bool VisitFixedPointLiteral(const FixedPointLiteral *E) {11684return Success(E->getValue(), E);11685}1168611687bool VisitCastExpr(const CastExpr *E);11688bool VisitUnaryOperator(const UnaryOperator *E);11689bool VisitBinaryOperator(const BinaryOperator *E);11690};11691} // end anonymous namespace1169211693/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and11694/// produce either the integer value or a pointer.11695///11696/// GCC has a heinous extension which folds casts between pointer types and11697/// pointer-sized integral types. We support this by allowing the evaluation of11698/// an integer rvalue to produce a pointer (represented as an lvalue) instead.11699/// Some simple arithmetic on such values is supported (they are treated much11700/// like char*).11701static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,11702EvalInfo &Info) {11703assert(!E->isValueDependent());11704assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());11705return IntExprEvaluator(Info, Result).Visit(E);11706}1170711708static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {11709assert(!E->isValueDependent());11710APValue Val;11711if (!EvaluateIntegerOrLValue(E, Val, Info))11712return false;11713if (!Val.isInt()) {11714// FIXME: It would be better to produce the diagnostic for casting11715// a pointer to an integer.11716Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);11717return false;11718}11719Result = Val.getInt();11720return true;11721}1172211723bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {11724APValue Evaluated = E->EvaluateInContext(11725Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());11726return Success(Evaluated, E);11727}1172811729static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,11730EvalInfo &Info) {11731assert(!E->isValueDependent());11732if (E->getType()->isFixedPointType()) {11733APValue Val;11734if (!FixedPointExprEvaluator(Info, Val).Visit(E))11735return false;11736if (!Val.isFixedPoint())11737return false;1173811739Result = Val.getFixedPoint();11740return true;11741}11742return false;11743}1174411745static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,11746EvalInfo &Info) {11747assert(!E->isValueDependent());11748if (E->getType()->isIntegerType()) {11749auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());11750APSInt Val;11751if (!EvaluateInteger(E, Val, Info))11752return false;11753Result = APFixedPoint(Val, FXSema);11754return true;11755} else if (E->getType()->isFixedPointType()) {11756return EvaluateFixedPoint(E, Result, Info);11757}11758return false;11759}1176011761/// Check whether the given declaration can be directly converted to an integral11762/// rvalue. If not, no diagnostic is produced; there are other things we can11763/// try.11764bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {11765// Enums are integer constant exprs.11766if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {11767// Check for signedness/width mismatches between E type and ECD value.11768bool SameSign = (ECD->getInitVal().isSigned()11769== E->getType()->isSignedIntegerOrEnumerationType());11770bool SameWidth = (ECD->getInitVal().getBitWidth()11771== Info.Ctx.getIntWidth(E->getType()));11772if (SameSign && SameWidth)11773return Success(ECD->getInitVal(), E);11774else {11775// Get rid of mismatch (otherwise Success assertions will fail)11776// by computing a new value matching the type of E.11777llvm::APSInt Val = ECD->getInitVal();11778if (!SameSign)11779Val.setIsSigned(!ECD->getInitVal().isSigned());11780if (!SameWidth)11781Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));11782return Success(Val, E);11783}11784}11785return false;11786}1178711788/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way11789/// as GCC.11790GCCTypeClass EvaluateBuiltinClassifyType(QualType T,11791const LangOptions &LangOpts) {11792assert(!T->isDependentType() && "unexpected dependent type");1179311794QualType CanTy = T.getCanonicalType();1179511796switch (CanTy->getTypeClass()) {11797#define TYPE(ID, BASE)11798#define DEPENDENT_TYPE(ID, BASE) case Type::ID:11799#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:11800#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:11801#include "clang/AST/TypeNodes.inc"11802case Type::Auto:11803case Type::DeducedTemplateSpecialization:11804llvm_unreachable("unexpected non-canonical or dependent type");1180511806case Type::Builtin:11807switch (cast<BuiltinType>(CanTy)->getKind()) {11808#define BUILTIN_TYPE(ID, SINGLETON_ID)11809#define SIGNED_TYPE(ID, SINGLETON_ID) \11810case BuiltinType::ID: return GCCTypeClass::Integer;11811#define FLOATING_TYPE(ID, SINGLETON_ID) \11812case BuiltinType::ID: return GCCTypeClass::RealFloat;11813#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \11814case BuiltinType::ID: break;11815#include "clang/AST/BuiltinTypes.def"11816case BuiltinType::Void:11817return GCCTypeClass::Void;1181811819case BuiltinType::Bool:11820return GCCTypeClass::Bool;1182111822case BuiltinType::Char_U:11823case BuiltinType::UChar:11824case BuiltinType::WChar_U:11825case BuiltinType::Char8:11826case BuiltinType::Char16:11827case BuiltinType::Char32:11828case BuiltinType::UShort:11829case BuiltinType::UInt:11830case BuiltinType::ULong:11831case BuiltinType::ULongLong:11832case BuiltinType::UInt128:11833return GCCTypeClass::Integer;1183411835case BuiltinType::UShortAccum:11836case BuiltinType::UAccum:11837case BuiltinType::ULongAccum:11838case BuiltinType::UShortFract:11839case BuiltinType::UFract:11840case BuiltinType::ULongFract:11841case BuiltinType::SatUShortAccum:11842case BuiltinType::SatUAccum:11843case BuiltinType::SatULongAccum:11844case BuiltinType::SatUShortFract:11845case BuiltinType::SatUFract:11846case BuiltinType::SatULongFract:11847return GCCTypeClass::None;1184811849case BuiltinType::NullPtr:1185011851case BuiltinType::ObjCId:11852case BuiltinType::ObjCClass:11853case BuiltinType::ObjCSel:11854#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \11855case BuiltinType::Id:11856#include "clang/Basic/OpenCLImageTypes.def"11857#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \11858case BuiltinType::Id:11859#include "clang/Basic/OpenCLExtensionTypes.def"11860case BuiltinType::OCLSampler:11861case BuiltinType::OCLEvent:11862case BuiltinType::OCLClkEvent:11863case BuiltinType::OCLQueue:11864case BuiltinType::OCLReserveID:11865#define SVE_TYPE(Name, Id, SingletonId) \11866case BuiltinType::Id:11867#include "clang/Basic/AArch64SVEACLETypes.def"11868#define PPC_VECTOR_TYPE(Name, Id, Size) \11869case BuiltinType::Id:11870#include "clang/Basic/PPCTypes.def"11871#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:11872#include "clang/Basic/RISCVVTypes.def"11873#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:11874#include "clang/Basic/WebAssemblyReferenceTypes.def"11875#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:11876#include "clang/Basic/AMDGPUTypes.def"11877return GCCTypeClass::None;1187811879case BuiltinType::Dependent:11880llvm_unreachable("unexpected dependent type");11881};11882llvm_unreachable("unexpected placeholder type");1188311884case Type::Enum:11885return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;1188611887case Type::Pointer:11888case Type::ConstantArray:11889case Type::VariableArray:11890case Type::IncompleteArray:11891case Type::FunctionNoProto:11892case Type::FunctionProto:11893case Type::ArrayParameter:11894return GCCTypeClass::Pointer;1189511896case Type::MemberPointer:11897return CanTy->isMemberDataPointerType()11898? GCCTypeClass::PointerToDataMember11899: GCCTypeClass::PointerToMemberFunction;1190011901case Type::Complex:11902return GCCTypeClass::Complex;1190311904case Type::Record:11905return CanTy->isUnionType() ? GCCTypeClass::Union11906: GCCTypeClass::ClassOrStruct;1190711908case Type::Atomic:11909// GCC classifies _Atomic T the same as T.11910return EvaluateBuiltinClassifyType(11911CanTy->castAs<AtomicType>()->getValueType(), LangOpts);1191211913case Type::Vector:11914case Type::ExtVector:11915return GCCTypeClass::Vector;1191611917case Type::BlockPointer:11918case Type::ConstantMatrix:11919case Type::ObjCObject:11920case Type::ObjCInterface:11921case Type::ObjCObjectPointer:11922case Type::Pipe:11923// Classify all other types that don't fit into the regular11924// classification the same way.11925return GCCTypeClass::None;1192611927case Type::BitInt:11928return GCCTypeClass::BitInt;1192911930case Type::LValueReference:11931case Type::RValueReference:11932llvm_unreachable("invalid type for expression");11933}1193411935llvm_unreachable("unexpected type class");11936}1193711938/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way11939/// as GCC.11940static GCCTypeClass11941EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {11942// If no argument was supplied, default to None. This isn't11943// ideal, however it is what gcc does.11944if (E->getNumArgs() == 0)11945return GCCTypeClass::None;1194611947// FIXME: Bizarrely, GCC treats a call with more than one argument as not11948// being an ICE, but still folds it to a constant using the type of the first11949// argument.11950return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);11951}1195211953/// EvaluateBuiltinConstantPForLValue - Determine the result of11954/// __builtin_constant_p when applied to the given pointer.11955///11956/// A pointer is only "constant" if it is null (or a pointer cast to integer)11957/// or it points to the first character of a string literal.11958static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {11959APValue::LValueBase Base = LV.getLValueBase();11960if (Base.isNull()) {11961// A null base is acceptable.11962return true;11963} else if (const Expr *E = Base.dyn_cast<const Expr *>()) {11964if (!isa<StringLiteral>(E))11965return false;11966return LV.getLValueOffset().isZero();11967} else if (Base.is<TypeInfoLValue>()) {11968// Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to11969// evaluate to true.11970return true;11971} else {11972// Any other base is not constant enough for GCC.11973return false;11974}11975}1197611977/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to11978/// GCC as we can manage.11979static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {11980// This evaluation is not permitted to have side-effects, so evaluate it in11981// a speculative evaluation context.11982SpeculativeEvaluationRAII SpeculativeEval(Info);1198311984// Constant-folding is always enabled for the operand of __builtin_constant_p11985// (even when the enclosing evaluation context otherwise requires a strict11986// language-specific constant expression).11987FoldConstant Fold(Info, true);1198811989QualType ArgType = Arg->getType();1199011991// __builtin_constant_p always has one operand. The rules which gcc follows11992// are not precisely documented, but are as follows:11993//11994// - If the operand is of integral, floating, complex or enumeration type,11995// and can be folded to a known value of that type, it returns 1.11996// - If the operand can be folded to a pointer to the first character11997// of a string literal (or such a pointer cast to an integral type)11998// or to a null pointer or an integer cast to a pointer, it returns 1.11999//12000// Otherwise, it returns 0.12001//12002// FIXME: GCC also intends to return 1 for literals of aggregate types, but12003// its support for this did not work prior to GCC 9 and is not yet well12004// understood.12005if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||12006ArgType->isAnyComplexType() || ArgType->isPointerType() ||12007ArgType->isNullPtrType()) {12008APValue V;12009if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {12010Fold.keepDiagnostics();12011return false;12012}1201312014// For a pointer (possibly cast to integer), there are special rules.12015if (V.getKind() == APValue::LValue)12016return EvaluateBuiltinConstantPForLValue(V);1201712018// Otherwise, any constant value is good enough.12019return V.hasValue();12020}1202112022// Anything else isn't considered to be sufficiently constant.12023return false;12024}1202512026/// Retrieves the "underlying object type" of the given expression,12027/// as used by __builtin_object_size.12028static QualType getObjectType(APValue::LValueBase B) {12029if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {12030if (const VarDecl *VD = dyn_cast<VarDecl>(D))12031return VD->getType();12032} else if (const Expr *E = B.dyn_cast<const Expr*>()) {12033if (isa<CompoundLiteralExpr>(E))12034return E->getType();12035} else if (B.is<TypeInfoLValue>()) {12036return B.getTypeInfoType();12037} else if (B.is<DynamicAllocLValue>()) {12038return B.getDynamicAllocType();12039}1204012041return QualType();12042}1204312044/// A more selective version of E->IgnoreParenCasts for12045/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only12046/// to change the type of E.12047/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`12048///12049/// Always returns an RValue with a pointer representation.12050static const Expr *ignorePointerCastsAndParens(const Expr *E) {12051assert(E->isPRValue() && E->getType()->hasPointerRepresentation());1205212053const Expr *NoParens = E->IgnoreParens();12054const auto *Cast = dyn_cast<CastExpr>(NoParens);12055if (Cast == nullptr)12056return NoParens;1205712058// We only conservatively allow a few kinds of casts, because this code is12059// inherently a simple solution that seeks to support the common case.12060auto CastKind = Cast->getCastKind();12061if (CastKind != CK_NoOp && CastKind != CK_BitCast &&12062CastKind != CK_AddressSpaceConversion)12063return NoParens;1206412065const auto *SubExpr = Cast->getSubExpr();12066if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())12067return NoParens;12068return ignorePointerCastsAndParens(SubExpr);12069}1207012071/// Checks to see if the given LValue's Designator is at the end of the LValue's12072/// record layout. e.g.12073/// struct { struct { int a, b; } fst, snd; } obj;12074/// obj.fst // no12075/// obj.snd // yes12076/// obj.fst.a // no12077/// obj.fst.b // no12078/// obj.snd.a // no12079/// obj.snd.b // yes12080///12081/// Please note: this function is specialized for how __builtin_object_size12082/// views "objects".12083///12084/// If this encounters an invalid RecordDecl or otherwise cannot determine the12085/// correct result, it will always return true.12086static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {12087assert(!LVal.Designator.Invalid);1208812089auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {12090const RecordDecl *Parent = FD->getParent();12091Invalid = Parent->isInvalidDecl();12092if (Invalid || Parent->isUnion())12093return true;12094const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);12095return FD->getFieldIndex() + 1 == Layout.getFieldCount();12096};1209712098auto &Base = LVal.getLValueBase();12099if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {12100if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {12101bool Invalid;12102if (!IsLastOrInvalidFieldDecl(FD, Invalid))12103return Invalid;12104} else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {12105for (auto *FD : IFD->chain()) {12106bool Invalid;12107if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))12108return Invalid;12109}12110}12111}1211212113unsigned I = 0;12114QualType BaseType = getType(Base);12115if (LVal.Designator.FirstEntryIsAnUnsizedArray) {12116// If we don't know the array bound, conservatively assume we're looking at12117// the final array element.12118++I;12119if (BaseType->isIncompleteArrayType())12120BaseType = Ctx.getAsArrayType(BaseType)->getElementType();12121else12122BaseType = BaseType->castAs<PointerType>()->getPointeeType();12123}1212412125for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {12126const auto &Entry = LVal.Designator.Entries[I];12127if (BaseType->isArrayType()) {12128// Because __builtin_object_size treats arrays as objects, we can ignore12129// the index iff this is the last array in the Designator.12130if (I + 1 == E)12131return true;12132const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));12133uint64_t Index = Entry.getAsArrayIndex();12134if (Index + 1 != CAT->getZExtSize())12135return false;12136BaseType = CAT->getElementType();12137} else if (BaseType->isAnyComplexType()) {12138const auto *CT = BaseType->castAs<ComplexType>();12139uint64_t Index = Entry.getAsArrayIndex();12140if (Index != 1)12141return false;12142BaseType = CT->getElementType();12143} else if (auto *FD = getAsField(Entry)) {12144bool Invalid;12145if (!IsLastOrInvalidFieldDecl(FD, Invalid))12146return Invalid;12147BaseType = FD->getType();12148} else {12149assert(getAsBaseClass(Entry) && "Expecting cast to a base class");12150return false;12151}12152}12153return true;12154}1215512156/// Tests to see if the LValue has a user-specified designator (that isn't12157/// necessarily valid). Note that this always returns 'true' if the LValue has12158/// an unsized array as its first designator entry, because there's currently no12159/// way to tell if the user typed *foo or foo[0].12160static bool refersToCompleteObject(const LValue &LVal) {12161if (LVal.Designator.Invalid)12162return false;1216312164if (!LVal.Designator.Entries.empty())12165return LVal.Designator.isMostDerivedAnUnsizedArray();1216612167if (!LVal.InvalidBase)12168return true;1216912170// If `E` is a MemberExpr, then the first part of the designator is hiding in12171// the LValueBase.12172const auto *E = LVal.Base.dyn_cast<const Expr *>();12173return !E || !isa<MemberExpr>(E);12174}1217512176/// Attempts to detect a user writing into a piece of memory that's impossible12177/// to figure out the size of by just using types.12178static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {12179const SubobjectDesignator &Designator = LVal.Designator;12180// Notes:12181// - Users can only write off of the end when we have an invalid base. Invalid12182// bases imply we don't know where the memory came from.12183// - We used to be a bit more aggressive here; we'd only be conservative if12184// the array at the end was flexible, or if it had 0 or 1 elements. This12185// broke some common standard library extensions (PR30346), but was12186// otherwise seemingly fine. It may be useful to reintroduce this behavior12187// with some sort of list. OTOH, it seems that GCC is always12188// conservative with the last element in structs (if it's an array), so our12189// current behavior is more compatible than an explicit list approach would12190// be.12191auto isFlexibleArrayMember = [&] {12192using FAMKind = LangOptions::StrictFlexArraysLevelKind;12193FAMKind StrictFlexArraysLevel =12194Ctx.getLangOpts().getStrictFlexArraysLevel();1219512196if (Designator.isMostDerivedAnUnsizedArray())12197return true;1219812199if (StrictFlexArraysLevel == FAMKind::Default)12200return true;1220112202if (Designator.getMostDerivedArraySize() == 0 &&12203StrictFlexArraysLevel != FAMKind::IncompleteOnly)12204return true;1220512206if (Designator.getMostDerivedArraySize() == 1 &&12207StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)12208return true;1220912210return false;12211};1221212213return LVal.InvalidBase &&12214Designator.Entries.size() == Designator.MostDerivedPathLength &&12215Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&12216isDesignatorAtObjectEnd(Ctx, LVal);12217}1221812219/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.12220/// Fails if the conversion would cause loss of precision.12221static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,12222CharUnits &Result) {12223auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();12224if (Int.ugt(CharUnitsMax))12225return false;12226Result = CharUnits::fromQuantity(Int.getZExtValue());12227return true;12228}1222912230/// If we're evaluating the object size of an instance of a struct that12231/// contains a flexible array member, add the size of the initializer.12232static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,12233const LValue &LV, CharUnits &Size) {12234if (!T.isNull() && T->isStructureType() &&12235T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())12236if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())12237if (const auto *VD = dyn_cast<VarDecl>(V))12238if (VD->hasInit())12239Size += VD->getFlexibleArrayInitChars(Info.Ctx);12240}1224112242/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will12243/// determine how many bytes exist from the beginning of the object to either12244/// the end of the current subobject, or the end of the object itself, depending12245/// on what the LValue looks like + the value of Type.12246///12247/// If this returns false, the value of Result is undefined.12248static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,12249unsigned Type, const LValue &LVal,12250CharUnits &EndOffset) {12251bool DetermineForCompleteObject = refersToCompleteObject(LVal);1225212253auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {12254if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())12255return false;12256return HandleSizeof(Info, ExprLoc, Ty, Result);12257};1225812259// We want to evaluate the size of the entire object. This is a valid fallback12260// for when Type=1 and the designator is invalid, because we're asked for an12261// upper-bound.12262if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {12263// Type=3 wants a lower bound, so we can't fall back to this.12264if (Type == 3 && !DetermineForCompleteObject)12265return false;1226612267llvm::APInt APEndOffset;12268if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&12269getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))12270return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);1227112272if (LVal.InvalidBase)12273return false;1227412275QualType BaseTy = getObjectType(LVal.getLValueBase());12276const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);12277addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);12278return Ret;12279}1228012281// We want to evaluate the size of a subobject.12282const SubobjectDesignator &Designator = LVal.Designator;1228312284// The following is a moderately common idiom in C:12285//12286// struct Foo { int a; char c[1]; };12287// struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));12288// strcpy(&F->c[0], Bar);12289//12290// In order to not break too much legacy code, we need to support it.12291if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {12292// If we can resolve this to an alloc_size call, we can hand that back,12293// because we know for certain how many bytes there are to write to.12294llvm::APInt APEndOffset;12295if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&12296getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))12297return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);1229812299// If we cannot determine the size of the initial allocation, then we can't12300// given an accurate upper-bound. However, we are still able to give12301// conservative lower-bounds for Type=3.12302if (Type == 1)12303return false;12304}1230512306CharUnits BytesPerElem;12307if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))12308return false;1230912310// According to the GCC documentation, we want the size of the subobject12311// denoted by the pointer. But that's not quite right -- what we actually12312// want is the size of the immediately-enclosing array, if there is one.12313int64_t ElemsRemaining;12314if (Designator.MostDerivedIsArrayElement &&12315Designator.Entries.size() == Designator.MostDerivedPathLength) {12316uint64_t ArraySize = Designator.getMostDerivedArraySize();12317uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();12318ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;12319} else {12320ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;12321}1232212323EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;12324return true;12325}1232612327/// Tries to evaluate the __builtin_object_size for @p E. If successful,12328/// returns true and stores the result in @p Size.12329///12330/// If @p WasError is non-null, this will report whether the failure to evaluate12331/// is to be treated as an Error in IntExprEvaluator.12332static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,12333EvalInfo &Info, uint64_t &Size) {12334// Determine the denoted object.12335LValue LVal;12336{12337// The operand of __builtin_object_size is never evaluated for side-effects.12338// If there are any, but we can determine the pointed-to object anyway, then12339// ignore the side-effects.12340SpeculativeEvaluationRAII SpeculativeEval(Info);12341IgnoreSideEffectsRAII Fold(Info);1234212343if (E->isGLValue()) {12344// It's possible for us to be given GLValues if we're called via12345// Expr::tryEvaluateObjectSize.12346APValue RVal;12347if (!EvaluateAsRValue(Info, E, RVal))12348return false;12349LVal.setFrom(Info.Ctx, RVal);12350} else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,12351/*InvalidBaseOK=*/true))12352return false;12353}1235412355// If we point to before the start of the object, there are no accessible12356// bytes.12357if (LVal.getLValueOffset().isNegative()) {12358Size = 0;12359return true;12360}1236112362CharUnits EndOffset;12363if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))12364return false;1236512366// If we've fallen outside of the end offset, just pretend there's nothing to12367// write to/read from.12368if (EndOffset <= LVal.getLValueOffset())12369Size = 0;12370else12371Size = (EndOffset - LVal.getLValueOffset()).getQuantity();12372return true;12373}1237412375bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {12376if (!IsConstantEvaluatedBuiltinCall(E))12377return ExprEvaluatorBaseTy::VisitCallExpr(E);12378return VisitBuiltinCallExpr(E, E->getBuiltinCallee());12379}1238012381static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,12382APValue &Val, APSInt &Alignment) {12383QualType SrcTy = E->getArg(0)->getType();12384if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))12385return false;12386// Even though we are evaluating integer expressions we could get a pointer12387// argument for the __builtin_is_aligned() case.12388if (SrcTy->isPointerType()) {12389LValue Ptr;12390if (!EvaluatePointer(E->getArg(0), Ptr, Info))12391return false;12392Ptr.moveInto(Val);12393} else if (!SrcTy->isIntegralOrEnumerationType()) {12394Info.FFDiag(E->getArg(0));12395return false;12396} else {12397APSInt SrcInt;12398if (!EvaluateInteger(E->getArg(0), SrcInt, Info))12399return false;12400assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&12401"Bit widths must be the same");12402Val = APValue(SrcInt);12403}12404assert(Val.hasValue());12405return true;12406}1240712408bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,12409unsigned BuiltinOp) {12410switch (BuiltinOp) {12411default:12412return false;1241312414case Builtin::BI__builtin_dynamic_object_size:12415case Builtin::BI__builtin_object_size: {12416// The type was checked when we built the expression.12417unsigned Type =12418E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();12419assert(Type <= 3 && "unexpected type");1242012421uint64_t Size;12422if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))12423return Success(Size, E);1242412425if (E->getArg(0)->HasSideEffects(Info.Ctx))12426return Success((Type & 2) ? 0 : -1, E);1242712428// Expression had no side effects, but we couldn't statically determine the12429// size of the referenced object.12430switch (Info.EvalMode) {12431case EvalInfo::EM_ConstantExpression:12432case EvalInfo::EM_ConstantFold:12433case EvalInfo::EM_IgnoreSideEffects:12434// Leave it to IR generation.12435return Error(E);12436case EvalInfo::EM_ConstantExpressionUnevaluated:12437// Reduce it to a constant now.12438return Success((Type & 2) ? 0 : -1, E);12439}1244012441llvm_unreachable("unexpected EvalMode");12442}1244312444case Builtin::BI__builtin_os_log_format_buffer_size: {12445analyze_os_log::OSLogBufferLayout Layout;12446analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);12447return Success(Layout.size().getQuantity(), E);12448}1244912450case Builtin::BI__builtin_is_aligned: {12451APValue Src;12452APSInt Alignment;12453if (!getBuiltinAlignArguments(E, Info, Src, Alignment))12454return false;12455if (Src.isLValue()) {12456// If we evaluated a pointer, check the minimum known alignment.12457LValue Ptr;12458Ptr.setFrom(Info.Ctx, Src);12459CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);12460CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);12461// We can return true if the known alignment at the computed offset is12462// greater than the requested alignment.12463assert(PtrAlign.isPowerOfTwo());12464assert(Alignment.isPowerOf2());12465if (PtrAlign.getQuantity() >= Alignment)12466return Success(1, E);12467// If the alignment is not known to be sufficient, some cases could still12468// be aligned at run time. However, if the requested alignment is less or12469// equal to the base alignment and the offset is not aligned, we know that12470// the run-time value can never be aligned.12471if (BaseAlignment.getQuantity() >= Alignment &&12472PtrAlign.getQuantity() < Alignment)12473return Success(0, E);12474// Otherwise we can't infer whether the value is sufficiently aligned.12475// TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)12476// in cases where we can't fully evaluate the pointer.12477Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)12478<< Alignment;12479return false;12480}12481assert(Src.isInt());12482return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);12483}12484case Builtin::BI__builtin_align_up: {12485APValue Src;12486APSInt Alignment;12487if (!getBuiltinAlignArguments(E, Info, Src, Alignment))12488return false;12489if (!Src.isInt())12490return Error(E);12491APSInt AlignedVal =12492APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),12493Src.getInt().isUnsigned());12494assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());12495return Success(AlignedVal, E);12496}12497case Builtin::BI__builtin_align_down: {12498APValue Src;12499APSInt Alignment;12500if (!getBuiltinAlignArguments(E, Info, Src, Alignment))12501return false;12502if (!Src.isInt())12503return Error(E);12504APSInt AlignedVal =12505APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());12506assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());12507return Success(AlignedVal, E);12508}1250912510case Builtin::BI__builtin_bitreverse8:12511case Builtin::BI__builtin_bitreverse16:12512case Builtin::BI__builtin_bitreverse32:12513case Builtin::BI__builtin_bitreverse64: {12514APSInt Val;12515if (!EvaluateInteger(E->getArg(0), Val, Info))12516return false;1251712518return Success(Val.reverseBits(), E);12519}1252012521case Builtin::BI__builtin_bswap16:12522case Builtin::BI__builtin_bswap32:12523case Builtin::BI__builtin_bswap64: {12524APSInt Val;12525if (!EvaluateInteger(E->getArg(0), Val, Info))12526return false;1252712528return Success(Val.byteSwap(), E);12529}1253012531case Builtin::BI__builtin_classify_type:12532return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);1253312534case Builtin::BI__builtin_clrsb:12535case Builtin::BI__builtin_clrsbl:12536case Builtin::BI__builtin_clrsbll: {12537APSInt Val;12538if (!EvaluateInteger(E->getArg(0), Val, Info))12539return false;1254012541return Success(Val.getBitWidth() - Val.getSignificantBits(), E);12542}1254312544case Builtin::BI__builtin_clz:12545case Builtin::BI__builtin_clzl:12546case Builtin::BI__builtin_clzll:12547case Builtin::BI__builtin_clzs:12548case Builtin::BI__builtin_clzg:12549case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes12550case Builtin::BI__lzcnt:12551case Builtin::BI__lzcnt64: {12552APSInt Val;12553if (!EvaluateInteger(E->getArg(0), Val, Info))12554return false;1255512556std::optional<APSInt> Fallback;12557if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {12558APSInt FallbackTemp;12559if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))12560return false;12561Fallback = FallbackTemp;12562}1256312564if (!Val) {12565if (Fallback)12566return Success(*Fallback, E);1256712568// When the argument is 0, the result of GCC builtins is undefined,12569// whereas for Microsoft intrinsics, the result is the bit-width of the12570// argument.12571bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&12572BuiltinOp != Builtin::BI__lzcnt &&12573BuiltinOp != Builtin::BI__lzcnt64;1257412575if (ZeroIsUndefined)12576return Error(E);12577}1257812579return Success(Val.countl_zero(), E);12580}1258112582case Builtin::BI__builtin_constant_p: {12583const Expr *Arg = E->getArg(0);12584if (EvaluateBuiltinConstantP(Info, Arg))12585return Success(true, E);12586if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {12587// Outside a constant context, eagerly evaluate to false in the presence12588// of side-effects in order to avoid -Wunsequenced false-positives in12589// a branch on __builtin_constant_p(expr).12590return Success(false, E);12591}12592Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);12593return false;12594}1259512596case Builtin::BI__builtin_is_constant_evaluated: {12597const auto *Callee = Info.CurrentCall->getCallee();12598if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&12599(Info.CallStackDepth == 1 ||12600(Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&12601Callee->getIdentifier() &&12602Callee->getIdentifier()->isStr("is_constant_evaluated")))) {12603// FIXME: Find a better way to avoid duplicated diagnostics.12604if (Info.EvalStatus.Diag)12605Info.report((Info.CallStackDepth == 1)12606? E->getExprLoc()12607: Info.CurrentCall->getCallRange().getBegin(),12608diag::warn_is_constant_evaluated_always_true_constexpr)12609<< (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"12610: "std::is_constant_evaluated");12611}1261212613return Success(Info.InConstantContext, E);12614}1261512616case Builtin::BI__builtin_ctz:12617case Builtin::BI__builtin_ctzl:12618case Builtin::BI__builtin_ctzll:12619case Builtin::BI__builtin_ctzs:12620case Builtin::BI__builtin_ctzg: {12621APSInt Val;12622if (!EvaluateInteger(E->getArg(0), Val, Info))12623return false;1262412625std::optional<APSInt> Fallback;12626if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {12627APSInt FallbackTemp;12628if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))12629return false;12630Fallback = FallbackTemp;12631}1263212633if (!Val) {12634if (Fallback)12635return Success(*Fallback, E);1263612637return Error(E);12638}1263912640return Success(Val.countr_zero(), E);12641}1264212643case Builtin::BI__builtin_eh_return_data_regno: {12644int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();12645Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);12646return Success(Operand, E);12647}1264812649case Builtin::BI__builtin_expect:12650case Builtin::BI__builtin_expect_with_probability:12651return Visit(E->getArg(0));1265212653case Builtin::BI__builtin_ptrauth_string_discriminator: {12654const auto *Literal =12655cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());12656uint64_t Result = getPointerAuthStableSipHash(Literal->getString());12657return Success(Result, E);12658}1265912660case Builtin::BI__builtin_ffs:12661case Builtin::BI__builtin_ffsl:12662case Builtin::BI__builtin_ffsll: {12663APSInt Val;12664if (!EvaluateInteger(E->getArg(0), Val, Info))12665return false;1266612667unsigned N = Val.countr_zero();12668return Success(N == Val.getBitWidth() ? 0 : N + 1, E);12669}1267012671case Builtin::BI__builtin_fpclassify: {12672APFloat Val(0.0);12673if (!EvaluateFloat(E->getArg(5), Val, Info))12674return false;12675unsigned Arg;12676switch (Val.getCategory()) {12677case APFloat::fcNaN: Arg = 0; break;12678case APFloat::fcInfinity: Arg = 1; break;12679case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;12680case APFloat::fcZero: Arg = 4; break;12681}12682return Visit(E->getArg(Arg));12683}1268412685case Builtin::BI__builtin_isinf_sign: {12686APFloat Val(0.0);12687return EvaluateFloat(E->getArg(0), Val, Info) &&12688Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);12689}1269012691case Builtin::BI__builtin_isinf: {12692APFloat Val(0.0);12693return EvaluateFloat(E->getArg(0), Val, Info) &&12694Success(Val.isInfinity() ? 1 : 0, E);12695}1269612697case Builtin::BI__builtin_isfinite: {12698APFloat Val(0.0);12699return EvaluateFloat(E->getArg(0), Val, Info) &&12700Success(Val.isFinite() ? 1 : 0, E);12701}1270212703case Builtin::BI__builtin_isnan: {12704APFloat Val(0.0);12705return EvaluateFloat(E->getArg(0), Val, Info) &&12706Success(Val.isNaN() ? 1 : 0, E);12707}1270812709case Builtin::BI__builtin_isnormal: {12710APFloat Val(0.0);12711return EvaluateFloat(E->getArg(0), Val, Info) &&12712Success(Val.isNormal() ? 1 : 0, E);12713}1271412715case Builtin::BI__builtin_issubnormal: {12716APFloat Val(0.0);12717return EvaluateFloat(E->getArg(0), Val, Info) &&12718Success(Val.isDenormal() ? 1 : 0, E);12719}1272012721case Builtin::BI__builtin_iszero: {12722APFloat Val(0.0);12723return EvaluateFloat(E->getArg(0), Val, Info) &&12724Success(Val.isZero() ? 1 : 0, E);12725}1272612727case Builtin::BI__builtin_issignaling: {12728APFloat Val(0.0);12729return EvaluateFloat(E->getArg(0), Val, Info) &&12730Success(Val.isSignaling() ? 1 : 0, E);12731}1273212733case Builtin::BI__builtin_isfpclass: {12734APSInt MaskVal;12735if (!EvaluateInteger(E->getArg(1), MaskVal, Info))12736return false;12737unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());12738APFloat Val(0.0);12739return EvaluateFloat(E->getArg(0), Val, Info) &&12740Success((Val.classify() & Test) ? 1 : 0, E);12741}1274212743case Builtin::BI__builtin_parity:12744case Builtin::BI__builtin_parityl:12745case Builtin::BI__builtin_parityll: {12746APSInt Val;12747if (!EvaluateInteger(E->getArg(0), Val, Info))12748return false;1274912750return Success(Val.popcount() % 2, E);12751}1275212753case Builtin::BI__builtin_popcount:12754case Builtin::BI__builtin_popcountl:12755case Builtin::BI__builtin_popcountll:12756case Builtin::BI__builtin_popcountg:12757case Builtin::BI__popcnt16: // Microsoft variants of popcount12758case Builtin::BI__popcnt:12759case Builtin::BI__popcnt64: {12760APSInt Val;12761if (!EvaluateInteger(E->getArg(0), Val, Info))12762return false;1276312764return Success(Val.popcount(), E);12765}1276612767case Builtin::BI__builtin_rotateleft8:12768case Builtin::BI__builtin_rotateleft16:12769case Builtin::BI__builtin_rotateleft32:12770case Builtin::BI__builtin_rotateleft64:12771case Builtin::BI_rotl8: // Microsoft variants of rotate right12772case Builtin::BI_rotl16:12773case Builtin::BI_rotl:12774case Builtin::BI_lrotl:12775case Builtin::BI_rotl64: {12776APSInt Val, Amt;12777if (!EvaluateInteger(E->getArg(0), Val, Info) ||12778!EvaluateInteger(E->getArg(1), Amt, Info))12779return false;1278012781return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);12782}1278312784case Builtin::BI__builtin_rotateright8:12785case Builtin::BI__builtin_rotateright16:12786case Builtin::BI__builtin_rotateright32:12787case Builtin::BI__builtin_rotateright64:12788case Builtin::BI_rotr8: // Microsoft variants of rotate right12789case Builtin::BI_rotr16:12790case Builtin::BI_rotr:12791case Builtin::BI_lrotr:12792case Builtin::BI_rotr64: {12793APSInt Val, Amt;12794if (!EvaluateInteger(E->getArg(0), Val, Info) ||12795!EvaluateInteger(E->getArg(1), Amt, Info))12796return false;1279712798return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);12799}1280012801case Builtin::BIstrlen:12802case Builtin::BIwcslen:12803// A call to strlen is not a constant expression.12804if (Info.getLangOpts().CPlusPlus11)12805Info.CCEDiag(E, diag::note_constexpr_invalid_function)12806<< /*isConstexpr*/ 0 << /*isConstructor*/ 012807<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();12808else12809Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);12810[[fallthrough]];12811case Builtin::BI__builtin_strlen:12812case Builtin::BI__builtin_wcslen: {12813// As an extension, we support __builtin_strlen() as a constant expression,12814// and support folding strlen() to a constant.12815uint64_t StrLen;12816if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))12817return Success(StrLen, E);12818return false;12819}1282012821case Builtin::BIstrcmp:12822case Builtin::BIwcscmp:12823case Builtin::BIstrncmp:12824case Builtin::BIwcsncmp:12825case Builtin::BImemcmp:12826case Builtin::BIbcmp:12827case Builtin::BIwmemcmp:12828// A call to strlen is not a constant expression.12829if (Info.getLangOpts().CPlusPlus11)12830Info.CCEDiag(E, diag::note_constexpr_invalid_function)12831<< /*isConstexpr*/ 0 << /*isConstructor*/ 012832<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();12833else12834Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);12835[[fallthrough]];12836case Builtin::BI__builtin_strcmp:12837case Builtin::BI__builtin_wcscmp:12838case Builtin::BI__builtin_strncmp:12839case Builtin::BI__builtin_wcsncmp:12840case Builtin::BI__builtin_memcmp:12841case Builtin::BI__builtin_bcmp:12842case Builtin::BI__builtin_wmemcmp: {12843LValue String1, String2;12844if (!EvaluatePointer(E->getArg(0), String1, Info) ||12845!EvaluatePointer(E->getArg(1), String2, Info))12846return false;1284712848uint64_t MaxLength = uint64_t(-1);12849if (BuiltinOp != Builtin::BIstrcmp &&12850BuiltinOp != Builtin::BIwcscmp &&12851BuiltinOp != Builtin::BI__builtin_strcmp &&12852BuiltinOp != Builtin::BI__builtin_wcscmp) {12853APSInt N;12854if (!EvaluateInteger(E->getArg(2), N, Info))12855return false;12856MaxLength = N.getZExtValue();12857}1285812859// Empty substrings compare equal by definition.12860if (MaxLength == 0u)12861return Success(0, E);1286212863if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||12864!String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||12865String1.Designator.Invalid || String2.Designator.Invalid)12866return false;1286712868QualType CharTy1 = String1.Designator.getType(Info.Ctx);12869QualType CharTy2 = String2.Designator.getType(Info.Ctx);1287012871bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||12872BuiltinOp == Builtin::BIbcmp ||12873BuiltinOp == Builtin::BI__builtin_memcmp ||12874BuiltinOp == Builtin::BI__builtin_bcmp;1287512876assert(IsRawByte ||12877(Info.Ctx.hasSameUnqualifiedType(12878CharTy1, E->getArg(0)->getType()->getPointeeType()) &&12879Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));1288012881// For memcmp, allow comparing any arrays of '[[un]signed] char' or12882// 'char8_t', but no other types.12883if (IsRawByte &&12884!(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {12885// FIXME: Consider using our bit_cast implementation to support this.12886Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)12887<< ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()12888<< CharTy1 << CharTy2;12889return false;12890}1289112892const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {12893return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&12894handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&12895Char1.isInt() && Char2.isInt();12896};12897const auto &AdvanceElems = [&] {12898return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&12899HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);12900};1290112902bool StopAtNull =12903(BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&12904BuiltinOp != Builtin::BIwmemcmp &&12905BuiltinOp != Builtin::BI__builtin_memcmp &&12906BuiltinOp != Builtin::BI__builtin_bcmp &&12907BuiltinOp != Builtin::BI__builtin_wmemcmp);12908bool IsWide = BuiltinOp == Builtin::BIwcscmp ||12909BuiltinOp == Builtin::BIwcsncmp ||12910BuiltinOp == Builtin::BIwmemcmp ||12911BuiltinOp == Builtin::BI__builtin_wcscmp ||12912BuiltinOp == Builtin::BI__builtin_wcsncmp ||12913BuiltinOp == Builtin::BI__builtin_wmemcmp;1291412915for (; MaxLength; --MaxLength) {12916APValue Char1, Char2;12917if (!ReadCurElems(Char1, Char2))12918return false;12919if (Char1.getInt().ne(Char2.getInt())) {12920if (IsWide) // wmemcmp compares with wchar_t signedness.12921return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);12922// memcmp always compares unsigned chars.12923return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);12924}12925if (StopAtNull && !Char1.getInt())12926return Success(0, E);12927assert(!(StopAtNull && !Char2.getInt()));12928if (!AdvanceElems())12929return false;12930}12931// We hit the strncmp / memcmp limit.12932return Success(0, E);12933}1293412935case Builtin::BI__atomic_always_lock_free:12936case Builtin::BI__atomic_is_lock_free:12937case Builtin::BI__c11_atomic_is_lock_free: {12938APSInt SizeVal;12939if (!EvaluateInteger(E->getArg(0), SizeVal, Info))12940return false;1294112942// For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power12943// of two less than or equal to the maximum inline atomic width, we know it12944// is lock-free. If the size isn't a power of two, or greater than the12945// maximum alignment where we promote atomics, we know it is not lock-free12946// (at least not in the sense of atomic_is_lock_free). Otherwise,12947// the answer can only be determined at runtime; for example, 16-byte12948// atomics have lock-free implementations on some, but not all,12949// x86-64 processors.1295012951// Check power-of-two.12952CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());12953if (Size.isPowerOfTwo()) {12954// Check against inlining width.12955unsigned InlineWidthBits =12956Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();12957if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {12958if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||12959Size == CharUnits::One())12960return Success(1, E);1296112962// If the pointer argument can be evaluated to a compile-time constant12963// integer (or nullptr), check if that value is appropriately aligned.12964const Expr *PtrArg = E->getArg(1);12965Expr::EvalResult ExprResult;12966APSInt IntResult;12967if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&12968ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),12969Info.Ctx) &&12970IntResult.isAligned(Size.getAsAlign()))12971return Success(1, E);1297212973// Otherwise, check if the type's alignment against Size.12974if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {12975// Drop the potential implicit-cast to 'const volatile void*', getting12976// the underlying type.12977if (ICE->getCastKind() == CK_BitCast)12978PtrArg = ICE->getSubExpr();12979}1298012981if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {12982QualType PointeeType = PtrTy->getPointeeType();12983if (!PointeeType->isIncompleteType() &&12984Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {12985// OK, we will inline operations on this object.12986return Success(1, E);12987}12988}12989}12990}1299112992return BuiltinOp == Builtin::BI__atomic_always_lock_free ?12993Success(0, E) : Error(E);12994}12995case Builtin::BI__builtin_addcb:12996case Builtin::BI__builtin_addcs:12997case Builtin::BI__builtin_addc:12998case Builtin::BI__builtin_addcl:12999case Builtin::BI__builtin_addcll:13000case Builtin::BI__builtin_subcb:13001case Builtin::BI__builtin_subcs:13002case Builtin::BI__builtin_subc:13003case Builtin::BI__builtin_subcl:13004case Builtin::BI__builtin_subcll: {13005LValue CarryOutLValue;13006APSInt LHS, RHS, CarryIn, CarryOut, Result;13007QualType ResultType = E->getArg(0)->getType();13008if (!EvaluateInteger(E->getArg(0), LHS, Info) ||13009!EvaluateInteger(E->getArg(1), RHS, Info) ||13010!EvaluateInteger(E->getArg(2), CarryIn, Info) ||13011!EvaluatePointer(E->getArg(3), CarryOutLValue, Info))13012return false;13013// Copy the number of bits and sign.13014Result = LHS;13015CarryOut = LHS;1301613017bool FirstOverflowed = false;13018bool SecondOverflowed = false;13019switch (BuiltinOp) {13020default:13021llvm_unreachable("Invalid value for BuiltinOp");13022case Builtin::BI__builtin_addcb:13023case Builtin::BI__builtin_addcs:13024case Builtin::BI__builtin_addc:13025case Builtin::BI__builtin_addcl:13026case Builtin::BI__builtin_addcll:13027Result =13028LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);13029break;13030case Builtin::BI__builtin_subcb:13031case Builtin::BI__builtin_subcs:13032case Builtin::BI__builtin_subc:13033case Builtin::BI__builtin_subcl:13034case Builtin::BI__builtin_subcll:13035Result =13036LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);13037break;13038}1303913040// It is possible for both overflows to happen but CGBuiltin uses an OR so13041// this is consistent.13042CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);13043APValue APV{CarryOut};13044if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))13045return false;13046return Success(Result, E);13047}13048case Builtin::BI__builtin_add_overflow:13049case Builtin::BI__builtin_sub_overflow:13050case Builtin::BI__builtin_mul_overflow:13051case Builtin::BI__builtin_sadd_overflow:13052case Builtin::BI__builtin_uadd_overflow:13053case Builtin::BI__builtin_uaddl_overflow:13054case Builtin::BI__builtin_uaddll_overflow:13055case Builtin::BI__builtin_usub_overflow:13056case Builtin::BI__builtin_usubl_overflow:13057case Builtin::BI__builtin_usubll_overflow:13058case Builtin::BI__builtin_umul_overflow:13059case Builtin::BI__builtin_umull_overflow:13060case Builtin::BI__builtin_umulll_overflow:13061case Builtin::BI__builtin_saddl_overflow:13062case Builtin::BI__builtin_saddll_overflow:13063case Builtin::BI__builtin_ssub_overflow:13064case Builtin::BI__builtin_ssubl_overflow:13065case Builtin::BI__builtin_ssubll_overflow:13066case Builtin::BI__builtin_smul_overflow:13067case Builtin::BI__builtin_smull_overflow:13068case Builtin::BI__builtin_smulll_overflow: {13069LValue ResultLValue;13070APSInt LHS, RHS;1307113072QualType ResultType = E->getArg(2)->getType()->getPointeeType();13073if (!EvaluateInteger(E->getArg(0), LHS, Info) ||13074!EvaluateInteger(E->getArg(1), RHS, Info) ||13075!EvaluatePointer(E->getArg(2), ResultLValue, Info))13076return false;1307713078APSInt Result;13079bool DidOverflow = false;1308013081// If the types don't have to match, enlarge all 3 to the largest of them.13082if (BuiltinOp == Builtin::BI__builtin_add_overflow ||13083BuiltinOp == Builtin::BI__builtin_sub_overflow ||13084BuiltinOp == Builtin::BI__builtin_mul_overflow) {13085bool IsSigned = LHS.isSigned() || RHS.isSigned() ||13086ResultType->isSignedIntegerOrEnumerationType();13087bool AllSigned = LHS.isSigned() && RHS.isSigned() &&13088ResultType->isSignedIntegerOrEnumerationType();13089uint64_t LHSSize = LHS.getBitWidth();13090uint64_t RHSSize = RHS.getBitWidth();13091uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);13092uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);1309313094// Add an additional bit if the signedness isn't uniformly agreed to. We13095// could do this ONLY if there is a signed and an unsigned that both have13096// MaxBits, but the code to check that is pretty nasty. The issue will be13097// caught in the shrink-to-result later anyway.13098if (IsSigned && !AllSigned)13099++MaxBits;1310013101LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);13102RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);13103Result = APSInt(MaxBits, !IsSigned);13104}1310513106// Find largest int.13107switch (BuiltinOp) {13108default:13109llvm_unreachable("Invalid value for BuiltinOp");13110case Builtin::BI__builtin_add_overflow:13111case Builtin::BI__builtin_sadd_overflow:13112case Builtin::BI__builtin_saddl_overflow:13113case Builtin::BI__builtin_saddll_overflow:13114case Builtin::BI__builtin_uadd_overflow:13115case Builtin::BI__builtin_uaddl_overflow:13116case Builtin::BI__builtin_uaddll_overflow:13117Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)13118: LHS.uadd_ov(RHS, DidOverflow);13119break;13120case Builtin::BI__builtin_sub_overflow:13121case Builtin::BI__builtin_ssub_overflow:13122case Builtin::BI__builtin_ssubl_overflow:13123case Builtin::BI__builtin_ssubll_overflow:13124case Builtin::BI__builtin_usub_overflow:13125case Builtin::BI__builtin_usubl_overflow:13126case Builtin::BI__builtin_usubll_overflow:13127Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)13128: LHS.usub_ov(RHS, DidOverflow);13129break;13130case Builtin::BI__builtin_mul_overflow:13131case Builtin::BI__builtin_smul_overflow:13132case Builtin::BI__builtin_smull_overflow:13133case Builtin::BI__builtin_smulll_overflow:13134case Builtin::BI__builtin_umul_overflow:13135case Builtin::BI__builtin_umull_overflow:13136case Builtin::BI__builtin_umulll_overflow:13137Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)13138: LHS.umul_ov(RHS, DidOverflow);13139break;13140}1314113142// In the case where multiple sizes are allowed, truncate and see if13143// the values are the same.13144if (BuiltinOp == Builtin::BI__builtin_add_overflow ||13145BuiltinOp == Builtin::BI__builtin_sub_overflow ||13146BuiltinOp == Builtin::BI__builtin_mul_overflow) {13147// APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,13148// since it will give us the behavior of a TruncOrSelf in the case where13149// its parameter <= its size. We previously set Result to be at least the13150// type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth13151// will work exactly like TruncOrSelf.13152APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));13153Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());1315413155if (!APSInt::isSameValue(Temp, Result))13156DidOverflow = true;13157Result = Temp;13158}1315913160APValue APV{Result};13161if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))13162return false;13163return Success(DidOverflow, E);13164}13165}13166}1316713168/// Determine whether this is a pointer past the end of the complete13169/// object referred to by the lvalue.13170static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,13171const LValue &LV) {13172// A null pointer can be viewed as being "past the end" but we don't13173// choose to look at it that way here.13174if (!LV.getLValueBase())13175return false;1317613177// If the designator is valid and refers to a subobject, we're not pointing13178// past the end.13179if (!LV.getLValueDesignator().Invalid &&13180!LV.getLValueDesignator().isOnePastTheEnd())13181return false;1318213183// A pointer to an incomplete type might be past-the-end if the type's size is13184// zero. We cannot tell because the type is incomplete.13185QualType Ty = getType(LV.getLValueBase());13186if (Ty->isIncompleteType())13187return true;1318813189// Can't be past the end of an invalid object.13190if (LV.getLValueDesignator().Invalid)13191return false;1319213193// We're a past-the-end pointer if we point to the byte after the object,13194// no matter what our type or path is.13195auto Size = Ctx.getTypeSizeInChars(Ty);13196return LV.getLValueOffset() == Size;13197}1319813199namespace {1320013201/// Data recursive integer evaluator of certain binary operators.13202///13203/// We use a data recursive algorithm for binary operators so that we are able13204/// to handle extreme cases of chained binary operators without causing stack13205/// overflow.13206class DataRecursiveIntBinOpEvaluator {13207struct EvalResult {13208APValue Val;13209bool Failed = false;1321013211EvalResult() = default;1321213213void swap(EvalResult &RHS) {13214Val.swap(RHS.Val);13215Failed = RHS.Failed;13216RHS.Failed = false;13217}13218};1321913220struct Job {13221const Expr *E;13222EvalResult LHSResult; // meaningful only for binary operator expression.13223enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;1322413225Job() = default;13226Job(Job &&) = default;1322713228void startSpeculativeEval(EvalInfo &Info) {13229SpecEvalRAII = SpeculativeEvaluationRAII(Info);13230}1323113232private:13233SpeculativeEvaluationRAII SpecEvalRAII;13234};1323513236SmallVector<Job, 16> Queue;1323713238IntExprEvaluator &IntEval;13239EvalInfo &Info;13240APValue &FinalResult;1324113242public:13243DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)13244: IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }1324513246/// True if \param E is a binary operator that we are going to handle13247/// data recursively.13248/// We handle binary operators that are comma, logical, or that have operands13249/// with integral or enumeration type.13250static bool shouldEnqueue(const BinaryOperator *E) {13251return E->getOpcode() == BO_Comma || E->isLogicalOp() ||13252(E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&13253E->getLHS()->getType()->isIntegralOrEnumerationType() &&13254E->getRHS()->getType()->isIntegralOrEnumerationType());13255}1325613257bool Traverse(const BinaryOperator *E) {13258enqueue(E);13259EvalResult PrevResult;13260while (!Queue.empty())13261process(PrevResult);1326213263if (PrevResult.Failed) return false;1326413265FinalResult.swap(PrevResult.Val);13266return true;13267}1326813269private:13270bool Success(uint64_t Value, const Expr *E, APValue &Result) {13271return IntEval.Success(Value, E, Result);13272}13273bool Success(const APSInt &Value, const Expr *E, APValue &Result) {13274return IntEval.Success(Value, E, Result);13275}13276bool Error(const Expr *E) {13277return IntEval.Error(E);13278}13279bool Error(const Expr *E, diag::kind D) {13280return IntEval.Error(E, D);13281}1328213283OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {13284return Info.CCEDiag(E, D);13285}1328613287// Returns true if visiting the RHS is necessary, false otherwise.13288bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,13289bool &SuppressRHSDiags);1329013291bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,13292const BinaryOperator *E, APValue &Result);1329313294void EvaluateExpr(const Expr *E, EvalResult &Result) {13295Result.Failed = !Evaluate(Result.Val, Info, E);13296if (Result.Failed)13297Result.Val = APValue();13298}1329913300void process(EvalResult &Result);1330113302void enqueue(const Expr *E) {13303E = E->IgnoreParens();13304Queue.resize(Queue.size()+1);13305Queue.back().E = E;13306Queue.back().Kind = Job::AnyExprKind;13307}13308};1330913310}1331113312bool DataRecursiveIntBinOpEvaluator::13313VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,13314bool &SuppressRHSDiags) {13315if (E->getOpcode() == BO_Comma) {13316// Ignore LHS but note if we could not evaluate it.13317if (LHSResult.Failed)13318return Info.noteSideEffect();13319return true;13320}1332113322if (E->isLogicalOp()) {13323bool LHSAsBool;13324if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {13325// We were able to evaluate the LHS, see if we can get away with not13326// evaluating the RHS: 0 && X -> 0, 1 || X -> 113327if (LHSAsBool == (E->getOpcode() == BO_LOr)) {13328Success(LHSAsBool, E, LHSResult.Val);13329return false; // Ignore RHS13330}13331} else {13332LHSResult.Failed = true;1333313334// Since we weren't able to evaluate the left hand side, it13335// might have had side effects.13336if (!Info.noteSideEffect())13337return false;1333813339// We can't evaluate the LHS; however, sometimes the result13340// is determined by the RHS: X && 0 -> 0, X || 1 -> 1.13341// Don't ignore RHS and suppress diagnostics from this arm.13342SuppressRHSDiags = true;13343}1334413345return true;13346}1334713348assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&13349E->getRHS()->getType()->isIntegralOrEnumerationType());1335013351if (LHSResult.Failed && !Info.noteFailure())13352return false; // Ignore RHS;1335313354return true;13355}1335613357static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,13358bool IsSub) {13359// Compute the new offset in the appropriate width, wrapping at 64 bits.13360// FIXME: When compiling for a 32-bit target, we should use 32-bit13361// offsets.13362assert(!LVal.hasLValuePath() && "have designator for integer lvalue");13363CharUnits &Offset = LVal.getLValueOffset();13364uint64_t Offset64 = Offset.getQuantity();13365uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();13366Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index6413367: Offset64 + Index64);13368}1336913370bool DataRecursiveIntBinOpEvaluator::13371VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,13372const BinaryOperator *E, APValue &Result) {13373if (E->getOpcode() == BO_Comma) {13374if (RHSResult.Failed)13375return false;13376Result = RHSResult.Val;13377return true;13378}1337913380if (E->isLogicalOp()) {13381bool lhsResult, rhsResult;13382bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);13383bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);1338413385if (LHSIsOK) {13386if (RHSIsOK) {13387if (E->getOpcode() == BO_LOr)13388return Success(lhsResult || rhsResult, E, Result);13389else13390return Success(lhsResult && rhsResult, E, Result);13391}13392} else {13393if (RHSIsOK) {13394// We can't evaluate the LHS; however, sometimes the result13395// is determined by the RHS: X && 0 -> 0, X || 1 -> 1.13396if (rhsResult == (E->getOpcode() == BO_LOr))13397return Success(rhsResult, E, Result);13398}13399}1340013401return false;13402}1340313404assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&13405E->getRHS()->getType()->isIntegralOrEnumerationType());1340613407if (LHSResult.Failed || RHSResult.Failed)13408return false;1340913410const APValue &LHSVal = LHSResult.Val;13411const APValue &RHSVal = RHSResult.Val;1341213413// Handle cases like (unsigned long)&a + 4.13414if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {13415Result = LHSVal;13416addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);13417return true;13418}1341913420// Handle cases like 4 + (unsigned long)&a13421if (E->getOpcode() == BO_Add &&13422RHSVal.isLValue() && LHSVal.isInt()) {13423Result = RHSVal;13424addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);13425return true;13426}1342713428if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {13429// Handle (intptr_t)&&A - (intptr_t)&&B.13430if (!LHSVal.getLValueOffset().isZero() ||13431!RHSVal.getLValueOffset().isZero())13432return false;13433const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();13434const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();13435if (!LHSExpr || !RHSExpr)13436return false;13437const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);13438const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);13439if (!LHSAddrExpr || !RHSAddrExpr)13440return false;13441// Make sure both labels come from the same function.13442if (LHSAddrExpr->getLabel()->getDeclContext() !=13443RHSAddrExpr->getLabel()->getDeclContext())13444return false;13445Result = APValue(LHSAddrExpr, RHSAddrExpr);13446return true;13447}1344813449// All the remaining cases expect both operands to be an integer13450if (!LHSVal.isInt() || !RHSVal.isInt())13451return Error(E);1345213453// Set up the width and signedness manually, in case it can't be deduced13454// from the operation we're performing.13455// FIXME: Don't do this in the cases where we can deduce it.13456APSInt Value(Info.Ctx.getIntWidth(E->getType()),13457E->getType()->isUnsignedIntegerOrEnumerationType());13458if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),13459RHSVal.getInt(), Value))13460return false;13461return Success(Value, E, Result);13462}1346313464void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {13465Job &job = Queue.back();1346613467switch (job.Kind) {13468case Job::AnyExprKind: {13469if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {13470if (shouldEnqueue(Bop)) {13471job.Kind = Job::BinOpKind;13472enqueue(Bop->getLHS());13473return;13474}13475}1347613477EvaluateExpr(job.E, Result);13478Queue.pop_back();13479return;13480}1348113482case Job::BinOpKind: {13483const BinaryOperator *Bop = cast<BinaryOperator>(job.E);13484bool SuppressRHSDiags = false;13485if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {13486Queue.pop_back();13487return;13488}13489if (SuppressRHSDiags)13490job.startSpeculativeEval(Info);13491job.LHSResult.swap(Result);13492job.Kind = Job::BinOpVisitedLHSKind;13493enqueue(Bop->getRHS());13494return;13495}1349613497case Job::BinOpVisitedLHSKind: {13498const BinaryOperator *Bop = cast<BinaryOperator>(job.E);13499EvalResult RHS;13500RHS.swap(Result);13501Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);13502Queue.pop_back();13503return;13504}13505}1350613507llvm_unreachable("Invalid Job::Kind!");13508}1350913510namespace {13511enum class CmpResult {13512Unequal,13513Less,13514Equal,13515Greater,13516Unordered,13517};13518}1351913520template <class SuccessCB, class AfterCB>13521static bool13522EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,13523SuccessCB &&Success, AfterCB &&DoAfter) {13524assert(!E->isValueDependent());13525assert(E->isComparisonOp() && "expected comparison operator");13526assert((E->getOpcode() == BO_Cmp ||13527E->getType()->isIntegralOrEnumerationType()) &&13528"unsupported binary expression evaluation");13529auto Error = [&](const Expr *E) {13530Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);13531return false;13532};1353313534bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;13535bool IsEquality = E->isEqualityOp();1353613537QualType LHSTy = E->getLHS()->getType();13538QualType RHSTy = E->getRHS()->getType();1353913540if (LHSTy->isIntegralOrEnumerationType() &&13541RHSTy->isIntegralOrEnumerationType()) {13542APSInt LHS, RHS;13543bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);13544if (!LHSOK && !Info.noteFailure())13545return false;13546if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)13547return false;13548if (LHS < RHS)13549return Success(CmpResult::Less, E);13550if (LHS > RHS)13551return Success(CmpResult::Greater, E);13552return Success(CmpResult::Equal, E);13553}1355413555if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {13556APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));13557APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));1355813559bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);13560if (!LHSOK && !Info.noteFailure())13561return false;13562if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)13563return false;13564if (LHSFX < RHSFX)13565return Success(CmpResult::Less, E);13566if (LHSFX > RHSFX)13567return Success(CmpResult::Greater, E);13568return Success(CmpResult::Equal, E);13569}1357013571if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {13572ComplexValue LHS, RHS;13573bool LHSOK;13574if (E->isAssignmentOp()) {13575LValue LV;13576EvaluateLValue(E->getLHS(), LV, Info);13577LHSOK = false;13578} else if (LHSTy->isRealFloatingType()) {13579LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);13580if (LHSOK) {13581LHS.makeComplexFloat();13582LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());13583}13584} else {13585LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);13586}13587if (!LHSOK && !Info.noteFailure())13588return false;1358913590if (E->getRHS()->getType()->isRealFloatingType()) {13591if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)13592return false;13593RHS.makeComplexFloat();13594RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());13595} else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)13596return false;1359713598if (LHS.isComplexFloat()) {13599APFloat::cmpResult CR_r =13600LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());13601APFloat::cmpResult CR_i =13602LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());13603bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;13604return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);13605} else {13606assert(IsEquality && "invalid complex comparison");13607bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&13608LHS.getComplexIntImag() == RHS.getComplexIntImag();13609return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);13610}13611}1361213613if (LHSTy->isRealFloatingType() &&13614RHSTy->isRealFloatingType()) {13615APFloat RHS(0.0), LHS(0.0);1361613617bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);13618if (!LHSOK && !Info.noteFailure())13619return false;1362013621if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)13622return false;1362313624assert(E->isComparisonOp() && "Invalid binary operator!");13625llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);13626if (!Info.InConstantContext &&13627APFloatCmpResult == APFloat::cmpUnordered &&13628E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {13629// Note: Compares may raise invalid in some cases involving NaN or sNaN.13630Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);13631return false;13632}13633auto GetCmpRes = [&]() {13634switch (APFloatCmpResult) {13635case APFloat::cmpEqual:13636return CmpResult::Equal;13637case APFloat::cmpLessThan:13638return CmpResult::Less;13639case APFloat::cmpGreaterThan:13640return CmpResult::Greater;13641case APFloat::cmpUnordered:13642return CmpResult::Unordered;13643}13644llvm_unreachable("Unrecognised APFloat::cmpResult enum");13645};13646return Success(GetCmpRes(), E);13647}1364813649if (LHSTy->isPointerType() && RHSTy->isPointerType()) {13650LValue LHSValue, RHSValue;1365113652bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);13653if (!LHSOK && !Info.noteFailure())13654return false;1365513656if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)13657return false;1365813659// Reject differing bases from the normal codepath; we special-case13660// comparisons to null.13661if (!HasSameBase(LHSValue, RHSValue)) {13662auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {13663std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());13664std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());13665Info.FFDiag(E, DiagID)13666<< (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);13667return false;13668};13669// Inequalities and subtractions between unrelated pointers have13670// unspecified or undefined behavior.13671if (!IsEquality)13672return DiagComparison(13673diag::note_constexpr_pointer_comparison_unspecified);13674// A constant address may compare equal to the address of a symbol.13675// The one exception is that address of an object cannot compare equal13676// to a null pointer constant.13677// TODO: Should we restrict this to actual null pointers, and exclude the13678// case of zero cast to pointer type?13679if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||13680(!RHSValue.Base && !RHSValue.Offset.isZero()))13681return DiagComparison(diag::note_constexpr_pointer_constant_comparison,13682!RHSValue.Base);13683// It's implementation-defined whether distinct literals will have13684// distinct addresses. In clang, the result of such a comparison is13685// unspecified, so it is not a constant expression. However, we do know13686// that the address of a literal will be non-null.13687if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&13688LHSValue.Base && RHSValue.Base)13689return DiagComparison(diag::note_constexpr_literal_comparison);13690// We can't tell whether weak symbols will end up pointing to the same13691// object.13692if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))13693return DiagComparison(diag::note_constexpr_pointer_weak_comparison,13694!IsWeakLValue(LHSValue));13695// We can't compare the address of the start of one object with the13696// past-the-end address of another object, per C++ DR1652.13697if (LHSValue.Base && LHSValue.Offset.isZero() &&13698isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))13699return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,13700true);13701if (RHSValue.Base && RHSValue.Offset.isZero() &&13702isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))13703return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,13704false);13705// We can't tell whether an object is at the same address as another13706// zero sized object.13707if ((RHSValue.Base && isZeroSized(LHSValue)) ||13708(LHSValue.Base && isZeroSized(RHSValue)))13709return DiagComparison(13710diag::note_constexpr_pointer_comparison_zero_sized);13711return Success(CmpResult::Unequal, E);13712}1371313714const CharUnits &LHSOffset = LHSValue.getLValueOffset();13715const CharUnits &RHSOffset = RHSValue.getLValueOffset();1371613717SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();13718SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();1371913720// C++11 [expr.rel]p3:13721// Pointers to void (after pointer conversions) can be compared, with a13722// result defined as follows: If both pointers represent the same13723// address or are both the null pointer value, the result is true if the13724// operator is <= or >= and false otherwise; otherwise the result is13725// unspecified.13726// We interpret this as applying to pointers to *cv* void.13727if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)13728Info.CCEDiag(E, diag::note_constexpr_void_comparison);1372913730// C++11 [expr.rel]p2:13731// - If two pointers point to non-static data members of the same object,13732// or to subobjects or array elements fo such members, recursively, the13733// pointer to the later declared member compares greater provided the13734// two members have the same access control and provided their class is13735// not a union.13736// [...]13737// - Otherwise pointer comparisons are unspecified.13738if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {13739bool WasArrayIndex;13740unsigned Mismatch = FindDesignatorMismatch(13741getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);13742// At the point where the designators diverge, the comparison has a13743// specified value if:13744// - we are comparing array indices13745// - we are comparing fields of a union, or fields with the same access13746// Otherwise, the result is unspecified and thus the comparison is not a13747// constant expression.13748if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&13749Mismatch < RHSDesignator.Entries.size()) {13750const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);13751const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);13752if (!LF && !RF)13753Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);13754else if (!LF)13755Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)13756<< getAsBaseClass(LHSDesignator.Entries[Mismatch])13757<< RF->getParent() << RF;13758else if (!RF)13759Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)13760<< getAsBaseClass(RHSDesignator.Entries[Mismatch])13761<< LF->getParent() << LF;13762else if (!LF->getParent()->isUnion() &&13763LF->getAccess() != RF->getAccess())13764Info.CCEDiag(E,13765diag::note_constexpr_pointer_comparison_differing_access)13766<< LF << LF->getAccess() << RF << RF->getAccess()13767<< LF->getParent();13768}13769}1377013771// The comparison here must be unsigned, and performed with the same13772// width as the pointer.13773unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);13774uint64_t CompareLHS = LHSOffset.getQuantity();13775uint64_t CompareRHS = RHSOffset.getQuantity();13776assert(PtrSize <= 64 && "Unexpected pointer width");13777uint64_t Mask = ~0ULL >> (64 - PtrSize);13778CompareLHS &= Mask;13779CompareRHS &= Mask;1378013781// If there is a base and this is a relational operator, we can only13782// compare pointers within the object in question; otherwise, the result13783// depends on where the object is located in memory.13784if (!LHSValue.Base.isNull() && IsRelational) {13785QualType BaseTy = getType(LHSValue.Base);13786if (BaseTy->isIncompleteType())13787return Error(E);13788CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);13789uint64_t OffsetLimit = Size.getQuantity();13790if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)13791return Error(E);13792}1379313794if (CompareLHS < CompareRHS)13795return Success(CmpResult::Less, E);13796if (CompareLHS > CompareRHS)13797return Success(CmpResult::Greater, E);13798return Success(CmpResult::Equal, E);13799}1380013801if (LHSTy->isMemberPointerType()) {13802assert(IsEquality && "unexpected member pointer operation");13803assert(RHSTy->isMemberPointerType() && "invalid comparison");1380413805MemberPtr LHSValue, RHSValue;1380613807bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);13808if (!LHSOK && !Info.noteFailure())13809return false;1381013811if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)13812return false;1381313814// If either operand is a pointer to a weak function, the comparison is not13815// constant.13816if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {13817Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)13818<< LHSValue.getDecl();13819return false;13820}13821if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {13822Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)13823<< RHSValue.getDecl();13824return false;13825}1382613827// C++11 [expr.eq]p2:13828// If both operands are null, they compare equal. Otherwise if only one is13829// null, they compare unequal.13830if (!LHSValue.getDecl() || !RHSValue.getDecl()) {13831bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();13832return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);13833}1383413835// Otherwise if either is a pointer to a virtual member function, the13836// result is unspecified.13837if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))13838if (MD->isVirtual())13839Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;13840if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))13841if (MD->isVirtual())13842Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;1384313844// Otherwise they compare equal if and only if they would refer to the13845// same member of the same most derived object or the same subobject if13846// they were dereferenced with a hypothetical object of the associated13847// class type.13848bool Equal = LHSValue == RHSValue;13849return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);13850}1385113852if (LHSTy->isNullPtrType()) {13853assert(E->isComparisonOp() && "unexpected nullptr operation");13854assert(RHSTy->isNullPtrType() && "missing pointer conversion");13855// C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t13856// are compared, the result is true of the operator is <=, >= or ==, and13857// false otherwise.13858LValue Res;13859if (!EvaluatePointer(E->getLHS(), Res, Info) ||13860!EvaluatePointer(E->getRHS(), Res, Info))13861return false;13862return Success(CmpResult::Equal, E);13863}1386413865return DoAfter();13866}1386713868bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {13869if (!CheckLiteralType(Info, E))13870return false;1387113872auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {13873ComparisonCategoryResult CCR;13874switch (CR) {13875case CmpResult::Unequal:13876llvm_unreachable("should never produce Unequal for three-way comparison");13877case CmpResult::Less:13878CCR = ComparisonCategoryResult::Less;13879break;13880case CmpResult::Equal:13881CCR = ComparisonCategoryResult::Equal;13882break;13883case CmpResult::Greater:13884CCR = ComparisonCategoryResult::Greater;13885break;13886case CmpResult::Unordered:13887CCR = ComparisonCategoryResult::Unordered;13888break;13889}13890// Evaluation succeeded. Lookup the information for the comparison category13891// type and fetch the VarDecl for the result.13892const ComparisonCategoryInfo &CmpInfo =13893Info.Ctx.CompCategories.getInfoForType(E->getType());13894const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;13895// Check and evaluate the result as a constant expression.13896LValue LV;13897LV.set(VD);13898if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))13899return false;13900return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,13901ConstantExprKind::Normal);13902};13903return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {13904return ExprEvaluatorBaseTy::VisitBinCmp(E);13905});13906}1390713908bool RecordExprEvaluator::VisitCXXParenListInitExpr(13909const CXXParenListInitExpr *E) {13910return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());13911}1391213913bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {13914// We don't support assignment in C. C++ assignments don't get here because13915// assignment is an lvalue in C++.13916if (E->isAssignmentOp()) {13917Error(E);13918if (!Info.noteFailure())13919return false;13920}1392113922if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))13923return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);1392413925assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||13926!E->getRHS()->getType()->isIntegralOrEnumerationType()) &&13927"DataRecursiveIntBinOpEvaluator should have handled integral types");1392813929if (E->isComparisonOp()) {13930// Evaluate builtin binary comparisons by evaluating them as three-way13931// comparisons and then translating the result.13932auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {13933assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&13934"should only produce Unequal for equality comparisons");13935bool IsEqual = CR == CmpResult::Equal,13936IsLess = CR == CmpResult::Less,13937IsGreater = CR == CmpResult::Greater;13938auto Op = E->getOpcode();13939switch (Op) {13940default:13941llvm_unreachable("unsupported binary operator");13942case BO_EQ:13943case BO_NE:13944return Success(IsEqual == (Op == BO_EQ), E);13945case BO_LT:13946return Success(IsLess, E);13947case BO_GT:13948return Success(IsGreater, E);13949case BO_LE:13950return Success(IsEqual || IsLess, E);13951case BO_GE:13952return Success(IsEqual || IsGreater, E);13953}13954};13955return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {13956return ExprEvaluatorBaseTy::VisitBinaryOperator(E);13957});13958}1395913960QualType LHSTy = E->getLHS()->getType();13961QualType RHSTy = E->getRHS()->getType();1396213963if (LHSTy->isPointerType() && RHSTy->isPointerType() &&13964E->getOpcode() == BO_Sub) {13965LValue LHSValue, RHSValue;1396613967bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);13968if (!LHSOK && !Info.noteFailure())13969return false;1397013971if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)13972return false;1397313974// Reject differing bases from the normal codepath; we special-case13975// comparisons to null.13976if (!HasSameBase(LHSValue, RHSValue)) {13977// Handle &&A - &&B.13978if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())13979return Error(E);13980const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();13981const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();13982if (!LHSExpr || !RHSExpr)13983return Error(E);13984const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);13985const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);13986if (!LHSAddrExpr || !RHSAddrExpr)13987return Error(E);13988// Make sure both labels come from the same function.13989if (LHSAddrExpr->getLabel()->getDeclContext() !=13990RHSAddrExpr->getLabel()->getDeclContext())13991return Error(E);13992return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);13993}13994const CharUnits &LHSOffset = LHSValue.getLValueOffset();13995const CharUnits &RHSOffset = RHSValue.getLValueOffset();1399613997SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();13998SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();1399914000// C++11 [expr.add]p6:14001// Unless both pointers point to elements of the same array object, or14002// one past the last element of the array object, the behavior is14003// undefined.14004if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&14005!AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,14006RHSDesignator))14007Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);1400814009QualType Type = E->getLHS()->getType();14010QualType ElementType = Type->castAs<PointerType>()->getPointeeType();1401114012CharUnits ElementSize;14013if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))14014return false;1401514016// As an extension, a type may have zero size (empty struct or union in14017// C, array of zero length). Pointer subtraction in such cases has14018// undefined behavior, so is not constant.14019if (ElementSize.isZero()) {14020Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)14021<< ElementType;14022return false;14023}1402414025// FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,14026// and produce incorrect results when it overflows. Such behavior14027// appears to be non-conforming, but is common, so perhaps we should14028// assume the standard intended for such cases to be undefined behavior14029// and check for them.1403014031// Compute (LHSOffset - RHSOffset) / Size carefully, checking for14032// overflow in the final conversion to ptrdiff_t.14033APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);14034APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);14035APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),14036false);14037APSInt TrueResult = (LHS - RHS) / ElemSize;14038APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));1403914040if (Result.extend(65) != TrueResult &&14041!HandleOverflow(Info, E, TrueResult, E->getType()))14042return false;14043return Success(Result, E);14044}1404514046return ExprEvaluatorBaseTy::VisitBinaryOperator(E);14047}1404814049/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with14050/// a result as the expression's type.14051bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(14052const UnaryExprOrTypeTraitExpr *E) {14053switch(E->getKind()) {14054case UETT_PreferredAlignOf:14055case UETT_AlignOf: {14056if (E->isArgumentType())14057return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),14058E);14059else14060return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),14061E);14062}1406314064case UETT_PtrAuthTypeDiscriminator: {14065if (E->getArgumentType()->isDependentType())14066return false;14067return Success(14068Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);14069}14070case UETT_VecStep: {14071QualType Ty = E->getTypeOfArgument();1407214073if (Ty->isVectorType()) {14074unsigned n = Ty->castAs<VectorType>()->getNumElements();1407514076// The vec_step built-in functions that take a 3-component14077// vector return 4. (OpenCL 1.1 spec 6.11.12)14078if (n == 3)14079n = 4;1408014081return Success(n, E);14082} else14083return Success(1, E);14084}1408514086case UETT_DataSizeOf:14087case UETT_SizeOf: {14088QualType SrcTy = E->getTypeOfArgument();14089// C++ [expr.sizeof]p2: "When applied to a reference or a reference type,14090// the result is the size of the referenced type."14091if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())14092SrcTy = Ref->getPointeeType();1409314094CharUnits Sizeof;14095if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,14096E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf14097: SizeOfType::SizeOf)) {14098return false;14099}14100return Success(Sizeof, E);14101}14102case UETT_OpenMPRequiredSimdAlign:14103assert(E->isArgumentType());14104return Success(14105Info.Ctx.toCharUnitsFromBits(14106Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))14107.getQuantity(),14108E);14109case UETT_VectorElements: {14110QualType Ty = E->getTypeOfArgument();14111// If the vector has a fixed size, we can determine the number of elements14112// at compile time.14113if (const auto *VT = Ty->getAs<VectorType>())14114return Success(VT->getNumElements(), E);1411514116assert(Ty->isSizelessVectorType());14117if (Info.InConstantContext)14118Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)14119<< E->getSourceRange();1412014121return false;14122}14123}1412414125llvm_unreachable("unknown expr/type trait");14126}1412714128bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {14129CharUnits Result;14130unsigned n = OOE->getNumComponents();14131if (n == 0)14132return Error(OOE);14133QualType CurrentType = OOE->getTypeSourceInfo()->getType();14134for (unsigned i = 0; i != n; ++i) {14135OffsetOfNode ON = OOE->getComponent(i);14136switch (ON.getKind()) {14137case OffsetOfNode::Array: {14138const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());14139APSInt IdxResult;14140if (!EvaluateInteger(Idx, IdxResult, Info))14141return false;14142const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);14143if (!AT)14144return Error(OOE);14145CurrentType = AT->getElementType();14146CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);14147Result += IdxResult.getSExtValue() * ElementSize;14148break;14149}1415014151case OffsetOfNode::Field: {14152FieldDecl *MemberDecl = ON.getField();14153const RecordType *RT = CurrentType->getAs<RecordType>();14154if (!RT)14155return Error(OOE);14156RecordDecl *RD = RT->getDecl();14157if (RD->isInvalidDecl()) return false;14158const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);14159unsigned i = MemberDecl->getFieldIndex();14160assert(i < RL.getFieldCount() && "offsetof field in wrong type");14161Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));14162CurrentType = MemberDecl->getType().getNonReferenceType();14163break;14164}1416514166case OffsetOfNode::Identifier:14167llvm_unreachable("dependent __builtin_offsetof");1416814169case OffsetOfNode::Base: {14170CXXBaseSpecifier *BaseSpec = ON.getBase();14171if (BaseSpec->isVirtual())14172return Error(OOE);1417314174// Find the layout of the class whose base we are looking into.14175const RecordType *RT = CurrentType->getAs<RecordType>();14176if (!RT)14177return Error(OOE);14178RecordDecl *RD = RT->getDecl();14179if (RD->isInvalidDecl()) return false;14180const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);1418114182// Find the base class itself.14183CurrentType = BaseSpec->getType();14184const RecordType *BaseRT = CurrentType->getAs<RecordType>();14185if (!BaseRT)14186return Error(OOE);1418714188// Add the offset to the base.14189Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));14190break;14191}14192}14193}14194return Success(Result, OOE);14195}1419614197bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {14198switch (E->getOpcode()) {14199default:14200// Address, indirect, pre/post inc/dec, etc are not valid constant exprs.14201// See C99 6.6p3.14202return Error(E);14203case UO_Extension:14204// FIXME: Should extension allow i-c-e extension expressions in its scope?14205// If so, we could clear the diagnostic ID.14206return Visit(E->getSubExpr());14207case UO_Plus:14208// The result is just the value.14209return Visit(E->getSubExpr());14210case UO_Minus: {14211if (!Visit(E->getSubExpr()))14212return false;14213if (!Result.isInt()) return Error(E);14214const APSInt &Value = Result.getInt();14215if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {14216if (Info.checkingForUndefinedBehavior())14217Info.Ctx.getDiagnostics().Report(E->getExprLoc(),14218diag::warn_integer_constant_overflow)14219<< toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,14220/*UpperCase=*/true, /*InsertSeparators=*/true)14221<< E->getType() << E->getSourceRange();1422214223if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),14224E->getType()))14225return false;14226}14227return Success(-Value, E);14228}14229case UO_Not: {14230if (!Visit(E->getSubExpr()))14231return false;14232if (!Result.isInt()) return Error(E);14233return Success(~Result.getInt(), E);14234}14235case UO_LNot: {14236bool bres;14237if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))14238return false;14239return Success(!bres, E);14240}14241}14242}1424314244/// HandleCast - This is used to evaluate implicit or explicit casts where the14245/// result type is integer.14246bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {14247const Expr *SubExpr = E->getSubExpr();14248QualType DestType = E->getType();14249QualType SrcType = SubExpr->getType();1425014251switch (E->getCastKind()) {14252case CK_BaseToDerived:14253case CK_DerivedToBase:14254case CK_UncheckedDerivedToBase:14255case CK_Dynamic:14256case CK_ToUnion:14257case CK_ArrayToPointerDecay:14258case CK_FunctionToPointerDecay:14259case CK_NullToPointer:14260case CK_NullToMemberPointer:14261case CK_BaseToDerivedMemberPointer:14262case CK_DerivedToBaseMemberPointer:14263case CK_ReinterpretMemberPointer:14264case CK_ConstructorConversion:14265case CK_IntegralToPointer:14266case CK_ToVoid:14267case CK_VectorSplat:14268case CK_IntegralToFloating:14269case CK_FloatingCast:14270case CK_CPointerToObjCPointerCast:14271case CK_BlockPointerToObjCPointerCast:14272case CK_AnyPointerToBlockPointerCast:14273case CK_ObjCObjectLValueCast:14274case CK_FloatingRealToComplex:14275case CK_FloatingComplexToReal:14276case CK_FloatingComplexCast:14277case CK_FloatingComplexToIntegralComplex:14278case CK_IntegralRealToComplex:14279case CK_IntegralComplexCast:14280case CK_IntegralComplexToFloatingComplex:14281case CK_BuiltinFnToFnPtr:14282case CK_ZeroToOCLOpaqueType:14283case CK_NonAtomicToAtomic:14284case CK_AddressSpaceConversion:14285case CK_IntToOCLSampler:14286case CK_FloatingToFixedPoint:14287case CK_FixedPointToFloating:14288case CK_FixedPointCast:14289case CK_IntegralToFixedPoint:14290case CK_MatrixCast:14291case CK_HLSLVectorTruncation:14292llvm_unreachable("invalid cast kind for integral value");1429314294case CK_BitCast:14295case CK_Dependent:14296case CK_LValueBitCast:14297case CK_ARCProduceObject:14298case CK_ARCConsumeObject:14299case CK_ARCReclaimReturnedObject:14300case CK_ARCExtendBlockObject:14301case CK_CopyAndAutoreleaseBlockObject:14302return Error(E);1430314304case CK_UserDefinedConversion:14305case CK_LValueToRValue:14306case CK_AtomicToNonAtomic:14307case CK_NoOp:14308case CK_LValueToRValueBitCast:14309case CK_HLSLArrayRValue:14310return ExprEvaluatorBaseTy::VisitCastExpr(E);1431114312case CK_MemberPointerToBoolean:14313case CK_PointerToBoolean:14314case CK_IntegralToBoolean:14315case CK_FloatingToBoolean:14316case CK_BooleanToSignedIntegral:14317case CK_FloatingComplexToBoolean:14318case CK_IntegralComplexToBoolean: {14319bool BoolResult;14320if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))14321return false;14322uint64_t IntResult = BoolResult;14323if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)14324IntResult = (uint64_t)-1;14325return Success(IntResult, E);14326}1432714328case CK_FixedPointToIntegral: {14329APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));14330if (!EvaluateFixedPoint(SubExpr, Src, Info))14331return false;14332bool Overflowed;14333llvm::APSInt Result = Src.convertToInt(14334Info.Ctx.getIntWidth(DestType),14335DestType->isSignedIntegerOrEnumerationType(), &Overflowed);14336if (Overflowed && !HandleOverflow(Info, E, Result, DestType))14337return false;14338return Success(Result, E);14339}1434014341case CK_FixedPointToBoolean: {14342// Unsigned padding does not affect this.14343APValue Val;14344if (!Evaluate(Val, Info, SubExpr))14345return false;14346return Success(Val.getFixedPoint().getBoolValue(), E);14347}1434814349case CK_IntegralCast: {14350if (!Visit(SubExpr))14351return false;1435214353if (!Result.isInt()) {14354// Allow casts of address-of-label differences if they are no-ops14355// or narrowing. (The narrowing case isn't actually guaranteed to14356// be constant-evaluatable except in some narrow cases which are hard14357// to detect here. We let it through on the assumption the user knows14358// what they are doing.)14359if (Result.isAddrLabelDiff())14360return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);14361// Only allow casts of lvalues if they are lossless.14362return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);14363}1436414365if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&14366Info.EvalMode == EvalInfo::EM_ConstantExpression &&14367DestType->isEnumeralType()) {1436814369bool ConstexprVar = true;1437014371// We know if we are here that we are in a context that we might require14372// a constant expression or a context that requires a constant14373// value. But if we are initializing a value we don't know if it is a14374// constexpr variable or not. We can check the EvaluatingDecl to determine14375// if it constexpr or not. If not then we don't want to emit a diagnostic.14376if (const auto *VD = dyn_cast_or_null<VarDecl>(14377Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))14378ConstexprVar = VD->isConstexpr();1437914380const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());14381const EnumDecl *ED = ET->getDecl();14382// Check that the value is within the range of the enumeration values.14383//14384// This corressponds to [expr.static.cast]p10 which says:14385// A value of integral or enumeration type can be explicitly converted14386// to a complete enumeration type ... If the enumeration type does not14387// have a fixed underlying type, the value is unchanged if the original14388// value is within the range of the enumeration values ([dcl.enum]), and14389// otherwise, the behavior is undefined.14390//14391// This was resolved as part of DR2338 which has CD5 status.14392if (!ED->isFixed()) {14393llvm::APInt Min;14394llvm::APInt Max;1439514396ED->getValueRange(Max, Min);14397--Max;1439814399if (ED->getNumNegativeBits() && ConstexprVar &&14400(Max.slt(Result.getInt().getSExtValue()) ||14401Min.sgt(Result.getInt().getSExtValue())))14402Info.Ctx.getDiagnostics().Report(14403E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)14404<< llvm::toString(Result.getInt(), 10) << Min.getSExtValue()14405<< Max.getSExtValue() << ED;14406else if (!ED->getNumNegativeBits() && ConstexprVar &&14407Max.ult(Result.getInt().getZExtValue()))14408Info.Ctx.getDiagnostics().Report(14409E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)14410<< llvm::toString(Result.getInt(), 10) << Min.getZExtValue()14411<< Max.getZExtValue() << ED;14412}14413}1441414415return Success(HandleIntToIntCast(Info, E, DestType, SrcType,14416Result.getInt()), E);14417}1441814419case CK_PointerToIntegral: {14420CCEDiag(E, diag::note_constexpr_invalid_cast)14421<< 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();1442214423LValue LV;14424if (!EvaluatePointer(SubExpr, LV, Info))14425return false;1442614427if (LV.getLValueBase()) {14428// Only allow based lvalue casts if they are lossless.14429// FIXME: Allow a larger integer size than the pointer size, and allow14430// narrowing back down to pointer width in subsequent integral casts.14431// FIXME: Check integer type's active bits, not its type size.14432if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))14433return Error(E);1443414435LV.Designator.setInvalid();14436LV.moveInto(Result);14437return true;14438}1443914440APSInt AsInt;14441APValue V;14442LV.moveInto(V);14443if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))14444llvm_unreachable("Can't cast this!");1444514446return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);14447}1444814449case CK_IntegralComplexToReal: {14450ComplexValue C;14451if (!EvaluateComplex(SubExpr, C, Info))14452return false;14453return Success(C.getComplexIntReal(), E);14454}1445514456case CK_FloatingToIntegral: {14457APFloat F(0.0);14458if (!EvaluateFloat(SubExpr, F, Info))14459return false;1446014461APSInt Value;14462if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))14463return false;14464return Success(Value, E);14465}14466}1446714468llvm_unreachable("unknown cast resulting in integral value");14469}1447014471bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {14472if (E->getSubExpr()->getType()->isAnyComplexType()) {14473ComplexValue LV;14474if (!EvaluateComplex(E->getSubExpr(), LV, Info))14475return false;14476if (!LV.isComplexInt())14477return Error(E);14478return Success(LV.getComplexIntReal(), E);14479}1448014481return Visit(E->getSubExpr());14482}1448314484bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {14485if (E->getSubExpr()->getType()->isComplexIntegerType()) {14486ComplexValue LV;14487if (!EvaluateComplex(E->getSubExpr(), LV, Info))14488return false;14489if (!LV.isComplexInt())14490return Error(E);14491return Success(LV.getComplexIntImag(), E);14492}1449314494VisitIgnoredValue(E->getSubExpr());14495return Success(0, E);14496}1449714498bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {14499return Success(E->getPackLength(), E);14500}1450114502bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {14503return Success(E->getValue(), E);14504}1450514506bool IntExprEvaluator::VisitConceptSpecializationExpr(14507const ConceptSpecializationExpr *E) {14508return Success(E->isSatisfied(), E);14509}1451014511bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {14512return Success(E->isSatisfied(), E);14513}1451414515bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {14516switch (E->getOpcode()) {14517default:14518// Invalid unary operators14519return Error(E);14520case UO_Plus:14521// The result is just the value.14522return Visit(E->getSubExpr());14523case UO_Minus: {14524if (!Visit(E->getSubExpr())) return false;14525if (!Result.isFixedPoint())14526return Error(E);14527bool Overflowed;14528APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);14529if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))14530return false;14531return Success(Negated, E);14532}14533case UO_LNot: {14534bool bres;14535if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))14536return false;14537return Success(!bres, E);14538}14539}14540}1454114542bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {14543const Expr *SubExpr = E->getSubExpr();14544QualType DestType = E->getType();14545assert(DestType->isFixedPointType() &&14546"Expected destination type to be a fixed point type");14547auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);1454814549switch (E->getCastKind()) {14550case CK_FixedPointCast: {14551APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));14552if (!EvaluateFixedPoint(SubExpr, Src, Info))14553return false;14554bool Overflowed;14555APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);14556if (Overflowed) {14557if (Info.checkingForUndefinedBehavior())14558Info.Ctx.getDiagnostics().Report(E->getExprLoc(),14559diag::warn_fixedpoint_constant_overflow)14560<< Result.toString() << E->getType();14561if (!HandleOverflow(Info, E, Result, E->getType()))14562return false;14563}14564return Success(Result, E);14565}14566case CK_IntegralToFixedPoint: {14567APSInt Src;14568if (!EvaluateInteger(SubExpr, Src, Info))14569return false;1457014571bool Overflowed;14572APFixedPoint IntResult = APFixedPoint::getFromIntValue(14573Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);1457414575if (Overflowed) {14576if (Info.checkingForUndefinedBehavior())14577Info.Ctx.getDiagnostics().Report(E->getExprLoc(),14578diag::warn_fixedpoint_constant_overflow)14579<< IntResult.toString() << E->getType();14580if (!HandleOverflow(Info, E, IntResult, E->getType()))14581return false;14582}1458314584return Success(IntResult, E);14585}14586case CK_FloatingToFixedPoint: {14587APFloat Src(0.0);14588if (!EvaluateFloat(SubExpr, Src, Info))14589return false;1459014591bool Overflowed;14592APFixedPoint Result = APFixedPoint::getFromFloatValue(14593Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);1459414595if (Overflowed) {14596if (Info.checkingForUndefinedBehavior())14597Info.Ctx.getDiagnostics().Report(E->getExprLoc(),14598diag::warn_fixedpoint_constant_overflow)14599<< Result.toString() << E->getType();14600if (!HandleOverflow(Info, E, Result, E->getType()))14601return false;14602}1460314604return Success(Result, E);14605}14606case CK_NoOp:14607case CK_LValueToRValue:14608return ExprEvaluatorBaseTy::VisitCastExpr(E);14609default:14610return Error(E);14611}14612}1461314614bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {14615if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)14616return ExprEvaluatorBaseTy::VisitBinaryOperator(E);1461714618const Expr *LHS = E->getLHS();14619const Expr *RHS = E->getRHS();14620FixedPointSemantics ResultFXSema =14621Info.Ctx.getFixedPointSemantics(E->getType());1462214623APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));14624if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))14625return false;14626APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));14627if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))14628return false;1462914630bool OpOverflow = false, ConversionOverflow = false;14631APFixedPoint Result(LHSFX.getSemantics());14632switch (E->getOpcode()) {14633case BO_Add: {14634Result = LHSFX.add(RHSFX, &OpOverflow)14635.convert(ResultFXSema, &ConversionOverflow);14636break;14637}14638case BO_Sub: {14639Result = LHSFX.sub(RHSFX, &OpOverflow)14640.convert(ResultFXSema, &ConversionOverflow);14641break;14642}14643case BO_Mul: {14644Result = LHSFX.mul(RHSFX, &OpOverflow)14645.convert(ResultFXSema, &ConversionOverflow);14646break;14647}14648case BO_Div: {14649if (RHSFX.getValue() == 0) {14650Info.FFDiag(E, diag::note_expr_divide_by_zero);14651return false;14652}14653Result = LHSFX.div(RHSFX, &OpOverflow)14654.convert(ResultFXSema, &ConversionOverflow);14655break;14656}14657case BO_Shl:14658case BO_Shr: {14659FixedPointSemantics LHSSema = LHSFX.getSemantics();14660llvm::APSInt RHSVal = RHSFX.getValue();1466114662unsigned ShiftBW =14663LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();14664unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);14665// Embedded-C 4.1.6.2.2:14666// The right operand must be nonnegative and less than the total number14667// of (nonpadding) bits of the fixed-point operand ...14668if (RHSVal.isNegative())14669Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;14670else if (Amt != RHSVal)14671Info.CCEDiag(E, diag::note_constexpr_large_shift)14672<< RHSVal << E->getType() << ShiftBW;1467314674if (E->getOpcode() == BO_Shl)14675Result = LHSFX.shl(Amt, &OpOverflow);14676else14677Result = LHSFX.shr(Amt, &OpOverflow);14678break;14679}14680default:14681return false;14682}14683if (OpOverflow || ConversionOverflow) {14684if (Info.checkingForUndefinedBehavior())14685Info.Ctx.getDiagnostics().Report(E->getExprLoc(),14686diag::warn_fixedpoint_constant_overflow)14687<< Result.toString() << E->getType();14688if (!HandleOverflow(Info, E, Result, E->getType()))14689return false;14690}14691return Success(Result, E);14692}1469314694//===----------------------------------------------------------------------===//14695// Float Evaluation14696//===----------------------------------------------------------------------===//1469714698namespace {14699class FloatExprEvaluator14700: public ExprEvaluatorBase<FloatExprEvaluator> {14701APFloat &Result;14702public:14703FloatExprEvaluator(EvalInfo &info, APFloat &result)14704: ExprEvaluatorBaseTy(info), Result(result) {}1470514706bool Success(const APValue &V, const Expr *e) {14707Result = V.getFloat();14708return true;14709}1471014711bool ZeroInitialization(const Expr *E) {14712Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));14713return true;14714}1471514716bool VisitCallExpr(const CallExpr *E);1471714718bool VisitUnaryOperator(const UnaryOperator *E);14719bool VisitBinaryOperator(const BinaryOperator *E);14720bool VisitFloatingLiteral(const FloatingLiteral *E);14721bool VisitCastExpr(const CastExpr *E);1472214723bool VisitUnaryReal(const UnaryOperator *E);14724bool VisitUnaryImag(const UnaryOperator *E);1472514726// FIXME: Missing: array subscript of vector, member of vector14727};14728} // end anonymous namespace1472914730static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {14731assert(!E->isValueDependent());14732assert(E->isPRValue() && E->getType()->isRealFloatingType());14733return FloatExprEvaluator(Info, Result).Visit(E);14734}1473514736static bool TryEvaluateBuiltinNaN(const ASTContext &Context,14737QualType ResultTy,14738const Expr *Arg,14739bool SNaN,14740llvm::APFloat &Result) {14741const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());14742if (!S) return false;1474314744const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);1474514746llvm::APInt fill;1474714748// Treat empty strings as if they were zero.14749if (S->getString().empty())14750fill = llvm::APInt(32, 0);14751else if (S->getString().getAsInteger(0, fill))14752return false;1475314754if (Context.getTargetInfo().isNan2008()) {14755if (SNaN)14756Result = llvm::APFloat::getSNaN(Sem, false, &fill);14757else14758Result = llvm::APFloat::getQNaN(Sem, false, &fill);14759} else {14760// Prior to IEEE 754-2008, architectures were allowed to choose whether14761// the first bit of their significand was set for qNaN or sNaN. MIPS chose14762// a different encoding to what became a standard in 2008, and for pre-14763// 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as14764// sNaN. This is now known as "legacy NaN" encoding.14765if (SNaN)14766Result = llvm::APFloat::getQNaN(Sem, false, &fill);14767else14768Result = llvm::APFloat::getSNaN(Sem, false, &fill);14769}1477014771return true;14772}1477314774bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {14775if (!IsConstantEvaluatedBuiltinCall(E))14776return ExprEvaluatorBaseTy::VisitCallExpr(E);1477714778switch (E->getBuiltinCallee()) {14779default:14780return false;1478114782case Builtin::BI__builtin_huge_val:14783case Builtin::BI__builtin_huge_valf:14784case Builtin::BI__builtin_huge_vall:14785case Builtin::BI__builtin_huge_valf16:14786case Builtin::BI__builtin_huge_valf128:14787case Builtin::BI__builtin_inf:14788case Builtin::BI__builtin_inff:14789case Builtin::BI__builtin_infl:14790case Builtin::BI__builtin_inff16:14791case Builtin::BI__builtin_inff128: {14792const llvm::fltSemantics &Sem =14793Info.Ctx.getFloatTypeSemantics(E->getType());14794Result = llvm::APFloat::getInf(Sem);14795return true;14796}1479714798case Builtin::BI__builtin_nans:14799case Builtin::BI__builtin_nansf:14800case Builtin::BI__builtin_nansl:14801case Builtin::BI__builtin_nansf16:14802case Builtin::BI__builtin_nansf128:14803if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),14804true, Result))14805return Error(E);14806return true;1480714808case Builtin::BI__builtin_nan:14809case Builtin::BI__builtin_nanf:14810case Builtin::BI__builtin_nanl:14811case Builtin::BI__builtin_nanf16:14812case Builtin::BI__builtin_nanf128:14813// If this is __builtin_nan() turn this into a nan, otherwise we14814// can't constant fold it.14815if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),14816false, Result))14817return Error(E);14818return true;1481914820case Builtin::BI__builtin_fabs:14821case Builtin::BI__builtin_fabsf:14822case Builtin::BI__builtin_fabsl:14823case Builtin::BI__builtin_fabsf128:14824// The C standard says "fabs raises no floating-point exceptions,14825// even if x is a signaling NaN. The returned value is independent of14826// the current rounding direction mode." Therefore constant folding can14827// proceed without regard to the floating point settings.14828// Reference, WG14 N2478 F.10.4.314829if (!EvaluateFloat(E->getArg(0), Result, Info))14830return false;1483114832if (Result.isNegative())14833Result.changeSign();14834return true;1483514836case Builtin::BI__arithmetic_fence:14837return EvaluateFloat(E->getArg(0), Result, Info);1483814839// FIXME: Builtin::BI__builtin_powi14840// FIXME: Builtin::BI__builtin_powif14841// FIXME: Builtin::BI__builtin_powil1484214843case Builtin::BI__builtin_copysign:14844case Builtin::BI__builtin_copysignf:14845case Builtin::BI__builtin_copysignl:14846case Builtin::BI__builtin_copysignf128: {14847APFloat RHS(0.);14848if (!EvaluateFloat(E->getArg(0), Result, Info) ||14849!EvaluateFloat(E->getArg(1), RHS, Info))14850return false;14851Result.copySign(RHS);14852return true;14853}1485414855case Builtin::BI__builtin_fmax:14856case Builtin::BI__builtin_fmaxf:14857case Builtin::BI__builtin_fmaxl:14858case Builtin::BI__builtin_fmaxf16:14859case Builtin::BI__builtin_fmaxf128: {14860// TODO: Handle sNaN.14861APFloat RHS(0.);14862if (!EvaluateFloat(E->getArg(0), Result, Info) ||14863!EvaluateFloat(E->getArg(1), RHS, Info))14864return false;14865// When comparing zeroes, return +0.0 if one of the zeroes is positive.14866if (Result.isZero() && RHS.isZero() && Result.isNegative())14867Result = RHS;14868else if (Result.isNaN() || RHS > Result)14869Result = RHS;14870return true;14871}1487214873case Builtin::BI__builtin_fmin:14874case Builtin::BI__builtin_fminf:14875case Builtin::BI__builtin_fminl:14876case Builtin::BI__builtin_fminf16:14877case Builtin::BI__builtin_fminf128: {14878// TODO: Handle sNaN.14879APFloat RHS(0.);14880if (!EvaluateFloat(E->getArg(0), Result, Info) ||14881!EvaluateFloat(E->getArg(1), RHS, Info))14882return false;14883// When comparing zeroes, return -0.0 if one of the zeroes is negative.14884if (Result.isZero() && RHS.isZero() && RHS.isNegative())14885Result = RHS;14886else if (Result.isNaN() || RHS < Result)14887Result = RHS;14888return true;14889}14890}14891}1489214893bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {14894if (E->getSubExpr()->getType()->isAnyComplexType()) {14895ComplexValue CV;14896if (!EvaluateComplex(E->getSubExpr(), CV, Info))14897return false;14898Result = CV.FloatReal;14899return true;14900}1490114902return Visit(E->getSubExpr());14903}1490414905bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {14906if (E->getSubExpr()->getType()->isAnyComplexType()) {14907ComplexValue CV;14908if (!EvaluateComplex(E->getSubExpr(), CV, Info))14909return false;14910Result = CV.FloatImag;14911return true;14912}1491314914VisitIgnoredValue(E->getSubExpr());14915const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());14916Result = llvm::APFloat::getZero(Sem);14917return true;14918}1491914920bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {14921switch (E->getOpcode()) {14922default: return Error(E);14923case UO_Plus:14924return EvaluateFloat(E->getSubExpr(), Result, Info);14925case UO_Minus:14926// In C standard, WG14 N2478 F.3 p414927// "the unary - raises no floating point exceptions,14928// even if the operand is signalling."14929if (!EvaluateFloat(E->getSubExpr(), Result, Info))14930return false;14931Result.changeSign();14932return true;14933}14934}1493514936bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {14937if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)14938return ExprEvaluatorBaseTy::VisitBinaryOperator(E);1493914940APFloat RHS(0.0);14941bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);14942if (!LHSOK && !Info.noteFailure())14943return false;14944return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&14945handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);14946}1494714948bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {14949Result = E->getValue();14950return true;14951}1495214953bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {14954const Expr* SubExpr = E->getSubExpr();1495514956switch (E->getCastKind()) {14957default:14958return ExprEvaluatorBaseTy::VisitCastExpr(E);1495914960case CK_IntegralToFloating: {14961APSInt IntResult;14962const FPOptions FPO = E->getFPFeaturesInEffect(14963Info.Ctx.getLangOpts());14964return EvaluateInteger(SubExpr, IntResult, Info) &&14965HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),14966IntResult, E->getType(), Result);14967}1496814969case CK_FixedPointToFloating: {14970APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));14971if (!EvaluateFixedPoint(SubExpr, FixResult, Info))14972return false;14973Result =14974FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));14975return true;14976}1497714978case CK_FloatingCast: {14979if (!Visit(SubExpr))14980return false;14981return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),14982Result);14983}1498414985case CK_FloatingComplexToReal: {14986ComplexValue V;14987if (!EvaluateComplex(SubExpr, V, Info))14988return false;14989Result = V.getComplexFloatReal();14990return true;14991}14992}14993}1499414995//===----------------------------------------------------------------------===//14996// Complex Evaluation (for float and integer)14997//===----------------------------------------------------------------------===//1499814999namespace {15000class ComplexExprEvaluator15001: public ExprEvaluatorBase<ComplexExprEvaluator> {15002ComplexValue &Result;1500315004public:15005ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)15006: ExprEvaluatorBaseTy(info), Result(Result) {}1500715008bool Success(const APValue &V, const Expr *e) {15009Result.setFrom(V);15010return true;15011}1501215013bool ZeroInitialization(const Expr *E);1501415015//===--------------------------------------------------------------------===//15016// Visitor Methods15017//===--------------------------------------------------------------------===//1501815019bool VisitImaginaryLiteral(const ImaginaryLiteral *E);15020bool VisitCastExpr(const CastExpr *E);15021bool VisitBinaryOperator(const BinaryOperator *E);15022bool VisitUnaryOperator(const UnaryOperator *E);15023bool VisitInitListExpr(const InitListExpr *E);15024bool VisitCallExpr(const CallExpr *E);15025};15026} // end anonymous namespace1502715028static bool EvaluateComplex(const Expr *E, ComplexValue &Result,15029EvalInfo &Info) {15030assert(!E->isValueDependent());15031assert(E->isPRValue() && E->getType()->isAnyComplexType());15032return ComplexExprEvaluator(Info, Result).Visit(E);15033}1503415035bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {15036QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();15037if (ElemTy->isRealFloatingType()) {15038Result.makeComplexFloat();15039APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));15040Result.FloatReal = Zero;15041Result.FloatImag = Zero;15042} else {15043Result.makeComplexInt();15044APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);15045Result.IntReal = Zero;15046Result.IntImag = Zero;15047}15048return true;15049}1505015051bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {15052const Expr* SubExpr = E->getSubExpr();1505315054if (SubExpr->getType()->isRealFloatingType()) {15055Result.makeComplexFloat();15056APFloat &Imag = Result.FloatImag;15057if (!EvaluateFloat(SubExpr, Imag, Info))15058return false;1505915060Result.FloatReal = APFloat(Imag.getSemantics());15061return true;15062} else {15063assert(SubExpr->getType()->isIntegerType() &&15064"Unexpected imaginary literal.");1506515066Result.makeComplexInt();15067APSInt &Imag = Result.IntImag;15068if (!EvaluateInteger(SubExpr, Imag, Info))15069return false;1507015071Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());15072return true;15073}15074}1507515076bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {1507715078switch (E->getCastKind()) {15079case CK_BitCast:15080case CK_BaseToDerived:15081case CK_DerivedToBase:15082case CK_UncheckedDerivedToBase:15083case CK_Dynamic:15084case CK_ToUnion:15085case CK_ArrayToPointerDecay:15086case CK_FunctionToPointerDecay:15087case CK_NullToPointer:15088case CK_NullToMemberPointer:15089case CK_BaseToDerivedMemberPointer:15090case CK_DerivedToBaseMemberPointer:15091case CK_MemberPointerToBoolean:15092case CK_ReinterpretMemberPointer:15093case CK_ConstructorConversion:15094case CK_IntegralToPointer:15095case CK_PointerToIntegral:15096case CK_PointerToBoolean:15097case CK_ToVoid:15098case CK_VectorSplat:15099case CK_IntegralCast:15100case CK_BooleanToSignedIntegral:15101case CK_IntegralToBoolean:15102case CK_IntegralToFloating:15103case CK_FloatingToIntegral:15104case CK_FloatingToBoolean:15105case CK_FloatingCast:15106case CK_CPointerToObjCPointerCast:15107case CK_BlockPointerToObjCPointerCast:15108case CK_AnyPointerToBlockPointerCast:15109case CK_ObjCObjectLValueCast:15110case CK_FloatingComplexToReal:15111case CK_FloatingComplexToBoolean:15112case CK_IntegralComplexToReal:15113case CK_IntegralComplexToBoolean:15114case CK_ARCProduceObject:15115case CK_ARCConsumeObject:15116case CK_ARCReclaimReturnedObject:15117case CK_ARCExtendBlockObject:15118case CK_CopyAndAutoreleaseBlockObject:15119case CK_BuiltinFnToFnPtr:15120case CK_ZeroToOCLOpaqueType:15121case CK_NonAtomicToAtomic:15122case CK_AddressSpaceConversion:15123case CK_IntToOCLSampler:15124case CK_FloatingToFixedPoint:15125case CK_FixedPointToFloating:15126case CK_FixedPointCast:15127case CK_FixedPointToBoolean:15128case CK_FixedPointToIntegral:15129case CK_IntegralToFixedPoint:15130case CK_MatrixCast:15131case CK_HLSLVectorTruncation:15132llvm_unreachable("invalid cast kind for complex value");1513315134case CK_LValueToRValue:15135case CK_AtomicToNonAtomic:15136case CK_NoOp:15137case CK_LValueToRValueBitCast:15138case CK_HLSLArrayRValue:15139return ExprEvaluatorBaseTy::VisitCastExpr(E);1514015141case CK_Dependent:15142case CK_LValueBitCast:15143case CK_UserDefinedConversion:15144return Error(E);1514515146case CK_FloatingRealToComplex: {15147APFloat &Real = Result.FloatReal;15148if (!EvaluateFloat(E->getSubExpr(), Real, Info))15149return false;1515015151Result.makeComplexFloat();15152Result.FloatImag = APFloat(Real.getSemantics());15153return true;15154}1515515156case CK_FloatingComplexCast: {15157if (!Visit(E->getSubExpr()))15158return false;1515915160QualType To = E->getType()->castAs<ComplexType>()->getElementType();15161QualType From15162= E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();1516315164return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&15165HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);15166}1516715168case CK_FloatingComplexToIntegralComplex: {15169if (!Visit(E->getSubExpr()))15170return false;1517115172QualType To = E->getType()->castAs<ComplexType>()->getElementType();15173QualType From15174= E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();15175Result.makeComplexInt();15176return HandleFloatToIntCast(Info, E, From, Result.FloatReal,15177To, Result.IntReal) &&15178HandleFloatToIntCast(Info, E, From, Result.FloatImag,15179To, Result.IntImag);15180}1518115182case CK_IntegralRealToComplex: {15183APSInt &Real = Result.IntReal;15184if (!EvaluateInteger(E->getSubExpr(), Real, Info))15185return false;1518615187Result.makeComplexInt();15188Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());15189return true;15190}1519115192case CK_IntegralComplexCast: {15193if (!Visit(E->getSubExpr()))15194return false;1519515196QualType To = E->getType()->castAs<ComplexType>()->getElementType();15197QualType From15198= E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();1519915200Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);15201Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);15202return true;15203}1520415205case CK_IntegralComplexToFloatingComplex: {15206if (!Visit(E->getSubExpr()))15207return false;1520815209const FPOptions FPO = E->getFPFeaturesInEffect(15210Info.Ctx.getLangOpts());15211QualType To = E->getType()->castAs<ComplexType>()->getElementType();15212QualType From15213= E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();15214Result.makeComplexFloat();15215return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,15216To, Result.FloatReal) &&15217HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,15218To, Result.FloatImag);15219}15220}1522115222llvm_unreachable("unknown cast resulting in complex value");15223}1522415225void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,15226APFloat &ResR, APFloat &ResI) {15227// This is an implementation of complex multiplication according to the15228// constraints laid out in C11 Annex G. The implementation uses the15229// following naming scheme:15230// (a + ib) * (c + id)1523115232APFloat AC = A * C;15233APFloat BD = B * D;15234APFloat AD = A * D;15235APFloat BC = B * C;15236ResR = AC - BD;15237ResI = AD + BC;15238if (ResR.isNaN() && ResI.isNaN()) {15239bool Recalc = false;15240if (A.isInfinity() || B.isInfinity()) {15241A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),15242A);15243B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),15244B);15245if (C.isNaN())15246C = APFloat::copySign(APFloat(C.getSemantics()), C);15247if (D.isNaN())15248D = APFloat::copySign(APFloat(D.getSemantics()), D);15249Recalc = true;15250}15251if (C.isInfinity() || D.isInfinity()) {15252C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),15253C);15254D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),15255D);15256if (A.isNaN())15257A = APFloat::copySign(APFloat(A.getSemantics()), A);15258if (B.isNaN())15259B = APFloat::copySign(APFloat(B.getSemantics()), B);15260Recalc = true;15261}15262if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||15263BC.isInfinity())) {15264if (A.isNaN())15265A = APFloat::copySign(APFloat(A.getSemantics()), A);15266if (B.isNaN())15267B = APFloat::copySign(APFloat(B.getSemantics()), B);15268if (C.isNaN())15269C = APFloat::copySign(APFloat(C.getSemantics()), C);15270if (D.isNaN())15271D = APFloat::copySign(APFloat(D.getSemantics()), D);15272Recalc = true;15273}15274if (Recalc) {15275ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);15276ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);15277}15278}15279}1528015281void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,15282APFloat &ResR, APFloat &ResI) {15283// This is an implementation of complex division according to the15284// constraints laid out in C11 Annex G. The implementation uses the15285// following naming scheme:15286// (a + ib) / (c + id)1528715288int DenomLogB = 0;15289APFloat MaxCD = maxnum(abs(C), abs(D));15290if (MaxCD.isFinite()) {15291DenomLogB = ilogb(MaxCD);15292C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);15293D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);15294}15295APFloat Denom = C * C + D * D;15296ResR =15297scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);15298ResI =15299scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);15300if (ResR.isNaN() && ResI.isNaN()) {15301if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {15302ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;15303ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;15304} else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&15305D.isFinite()) {15306A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),15307A);15308B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),15309B);15310ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);15311ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);15312} else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {15313C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),15314C);15315D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),15316D);15317ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);15318ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);15319}15320}15321}1532215323bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {15324if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)15325return ExprEvaluatorBaseTy::VisitBinaryOperator(E);1532615327// Track whether the LHS or RHS is real at the type system level. When this is15328// the case we can simplify our evaluation strategy.15329bool LHSReal = false, RHSReal = false;1533015331bool LHSOK;15332if (E->getLHS()->getType()->isRealFloatingType()) {15333LHSReal = true;15334APFloat &Real = Result.FloatReal;15335LHSOK = EvaluateFloat(E->getLHS(), Real, Info);15336if (LHSOK) {15337Result.makeComplexFloat();15338Result.FloatImag = APFloat(Real.getSemantics());15339}15340} else {15341LHSOK = Visit(E->getLHS());15342}15343if (!LHSOK && !Info.noteFailure())15344return false;1534515346ComplexValue RHS;15347if (E->getRHS()->getType()->isRealFloatingType()) {15348RHSReal = true;15349APFloat &Real = RHS.FloatReal;15350if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)15351return false;15352RHS.makeComplexFloat();15353RHS.FloatImag = APFloat(Real.getSemantics());15354} else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)15355return false;1535615357assert(!(LHSReal && RHSReal) &&15358"Cannot have both operands of a complex operation be real.");15359switch (E->getOpcode()) {15360default: return Error(E);15361case BO_Add:15362if (Result.isComplexFloat()) {15363Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),15364APFloat::rmNearestTiesToEven);15365if (LHSReal)15366Result.getComplexFloatImag() = RHS.getComplexFloatImag();15367else if (!RHSReal)15368Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),15369APFloat::rmNearestTiesToEven);15370} else {15371Result.getComplexIntReal() += RHS.getComplexIntReal();15372Result.getComplexIntImag() += RHS.getComplexIntImag();15373}15374break;15375case BO_Sub:15376if (Result.isComplexFloat()) {15377Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),15378APFloat::rmNearestTiesToEven);15379if (LHSReal) {15380Result.getComplexFloatImag() = RHS.getComplexFloatImag();15381Result.getComplexFloatImag().changeSign();15382} else if (!RHSReal) {15383Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),15384APFloat::rmNearestTiesToEven);15385}15386} else {15387Result.getComplexIntReal() -= RHS.getComplexIntReal();15388Result.getComplexIntImag() -= RHS.getComplexIntImag();15389}15390break;15391case BO_Mul:15392if (Result.isComplexFloat()) {15393// This is an implementation of complex multiplication according to the15394// constraints laid out in C11 Annex G. The implementation uses the15395// following naming scheme:15396// (a + ib) * (c + id)15397ComplexValue LHS = Result;15398APFloat &A = LHS.getComplexFloatReal();15399APFloat &B = LHS.getComplexFloatImag();15400APFloat &C = RHS.getComplexFloatReal();15401APFloat &D = RHS.getComplexFloatImag();15402APFloat &ResR = Result.getComplexFloatReal();15403APFloat &ResI = Result.getComplexFloatImag();15404if (LHSReal) {15405assert(!RHSReal && "Cannot have two real operands for a complex op!");15406ResR = A;15407ResI = A;15408// ResR = A * C;15409// ResI = A * D;15410if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||15411!handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))15412return false;15413} else if (RHSReal) {15414// ResR = C * A;15415// ResI = C * B;15416ResR = C;15417ResI = C;15418if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||15419!handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))15420return false;15421} else {15422HandleComplexComplexMul(A, B, C, D, ResR, ResI);15423}15424} else {15425ComplexValue LHS = Result;15426Result.getComplexIntReal() =15427(LHS.getComplexIntReal() * RHS.getComplexIntReal() -15428LHS.getComplexIntImag() * RHS.getComplexIntImag());15429Result.getComplexIntImag() =15430(LHS.getComplexIntReal() * RHS.getComplexIntImag() +15431LHS.getComplexIntImag() * RHS.getComplexIntReal());15432}15433break;15434case BO_Div:15435if (Result.isComplexFloat()) {15436// This is an implementation of complex division according to the15437// constraints laid out in C11 Annex G. The implementation uses the15438// following naming scheme:15439// (a + ib) / (c + id)15440ComplexValue LHS = Result;15441APFloat &A = LHS.getComplexFloatReal();15442APFloat &B = LHS.getComplexFloatImag();15443APFloat &C = RHS.getComplexFloatReal();15444APFloat &D = RHS.getComplexFloatImag();15445APFloat &ResR = Result.getComplexFloatReal();15446APFloat &ResI = Result.getComplexFloatImag();15447if (RHSReal) {15448ResR = A;15449ResI = B;15450// ResR = A / C;15451// ResI = B / C;15452if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||15453!handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))15454return false;15455} else {15456if (LHSReal) {15457// No real optimizations we can do here, stub out with zero.15458B = APFloat::getZero(A.getSemantics());15459}15460HandleComplexComplexDiv(A, B, C, D, ResR, ResI);15461}15462} else {15463if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)15464return Error(E, diag::note_expr_divide_by_zero);1546515466ComplexValue LHS = Result;15467APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +15468RHS.getComplexIntImag() * RHS.getComplexIntImag();15469Result.getComplexIntReal() =15470(LHS.getComplexIntReal() * RHS.getComplexIntReal() +15471LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;15472Result.getComplexIntImag() =15473(LHS.getComplexIntImag() * RHS.getComplexIntReal() -15474LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;15475}15476break;15477}1547815479return true;15480}1548115482bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {15483// Get the operand value into 'Result'.15484if (!Visit(E->getSubExpr()))15485return false;1548615487switch (E->getOpcode()) {15488default:15489return Error(E);15490case UO_Extension:15491return true;15492case UO_Plus:15493// The result is always just the subexpr.15494return true;15495case UO_Minus:15496if (Result.isComplexFloat()) {15497Result.getComplexFloatReal().changeSign();15498Result.getComplexFloatImag().changeSign();15499}15500else {15501Result.getComplexIntReal() = -Result.getComplexIntReal();15502Result.getComplexIntImag() = -Result.getComplexIntImag();15503}15504return true;15505case UO_Not:15506if (Result.isComplexFloat())15507Result.getComplexFloatImag().changeSign();15508else15509Result.getComplexIntImag() = -Result.getComplexIntImag();15510return true;15511}15512}1551315514bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {15515if (E->getNumInits() == 2) {15516if (E->getType()->isComplexType()) {15517Result.makeComplexFloat();15518if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))15519return false;15520if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))15521return false;15522} else {15523Result.makeComplexInt();15524if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))15525return false;15526if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))15527return false;15528}15529return true;15530}15531return ExprEvaluatorBaseTy::VisitInitListExpr(E);15532}1553315534bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {15535if (!IsConstantEvaluatedBuiltinCall(E))15536return ExprEvaluatorBaseTy::VisitCallExpr(E);1553715538switch (E->getBuiltinCallee()) {15539case Builtin::BI__builtin_complex:15540Result.makeComplexFloat();15541if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))15542return false;15543if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))15544return false;15545return true;1554615547default:15548return false;15549}15550}1555115552//===----------------------------------------------------------------------===//15553// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic15554// implicit conversion.15555//===----------------------------------------------------------------------===//1555615557namespace {15558class AtomicExprEvaluator :15559public ExprEvaluatorBase<AtomicExprEvaluator> {15560const LValue *This;15561APValue &Result;15562public:15563AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)15564: ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}1556515566bool Success(const APValue &V, const Expr *E) {15567Result = V;15568return true;15569}1557015571bool ZeroInitialization(const Expr *E) {15572ImplicitValueInitExpr VIE(15573E->getType()->castAs<AtomicType>()->getValueType());15574// For atomic-qualified class (and array) types in C++, initialize the15575// _Atomic-wrapped subobject directly, in-place.15576return This ? EvaluateInPlace(Result, Info, *This, &VIE)15577: Evaluate(Result, Info, &VIE);15578}1557915580bool VisitCastExpr(const CastExpr *E) {15581switch (E->getCastKind()) {15582default:15583return ExprEvaluatorBaseTy::VisitCastExpr(E);15584case CK_NullToPointer:15585VisitIgnoredValue(E->getSubExpr());15586return ZeroInitialization(E);15587case CK_NonAtomicToAtomic:15588return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())15589: Evaluate(Result, Info, E->getSubExpr());15590}15591}15592};15593} // end anonymous namespace1559415595static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,15596EvalInfo &Info) {15597assert(!E->isValueDependent());15598assert(E->isPRValue() && E->getType()->isAtomicType());15599return AtomicExprEvaluator(Info, This, Result).Visit(E);15600}1560115602//===----------------------------------------------------------------------===//15603// Void expression evaluation, primarily for a cast to void on the LHS of a15604// comma operator15605//===----------------------------------------------------------------------===//1560615607namespace {15608class VoidExprEvaluator15609: public ExprEvaluatorBase<VoidExprEvaluator> {15610public:15611VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}1561215613bool Success(const APValue &V, const Expr *e) { return true; }1561415615bool ZeroInitialization(const Expr *E) { return true; }1561615617bool VisitCastExpr(const CastExpr *E) {15618switch (E->getCastKind()) {15619default:15620return ExprEvaluatorBaseTy::VisitCastExpr(E);15621case CK_ToVoid:15622VisitIgnoredValue(E->getSubExpr());15623return true;15624}15625}1562615627bool VisitCallExpr(const CallExpr *E) {15628if (!IsConstantEvaluatedBuiltinCall(E))15629return ExprEvaluatorBaseTy::VisitCallExpr(E);1563015631switch (E->getBuiltinCallee()) {15632case Builtin::BI__assume:15633case Builtin::BI__builtin_assume:15634// The argument is not evaluated!15635return true;1563615637case Builtin::BI__builtin_operator_delete:15638return HandleOperatorDeleteCall(Info, E);1563915640default:15641return false;15642}15643}1564415645bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);15646};15647} // end anonymous namespace1564815649bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {15650// We cannot speculatively evaluate a delete expression.15651if (Info.SpeculativeEvaluationDepth)15652return false;1565315654FunctionDecl *OperatorDelete = E->getOperatorDelete();15655if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {15656Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)15657<< isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;15658return false;15659}1566015661const Expr *Arg = E->getArgument();1566215663LValue Pointer;15664if (!EvaluatePointer(Arg, Pointer, Info))15665return false;15666if (Pointer.Designator.Invalid)15667return false;1566815669// Deleting a null pointer has no effect.15670if (Pointer.isNullPointer()) {15671// This is the only case where we need to produce an extension warning:15672// the only other way we can succeed is if we find a dynamic allocation,15673// and we will have warned when we allocated it in that case.15674if (!Info.getLangOpts().CPlusPlus20)15675Info.CCEDiag(E, diag::note_constexpr_new);15676return true;15677}1567815679std::optional<DynAlloc *> Alloc = CheckDeleteKind(15680Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);15681if (!Alloc)15682return false;15683QualType AllocType = Pointer.Base.getDynamicAllocType();1568415685// For the non-array case, the designator must be empty if the static type15686// does not have a virtual destructor.15687if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&15688!hasVirtualDestructor(Arg->getType()->getPointeeType())) {15689Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)15690<< Arg->getType()->getPointeeType() << AllocType;15691return false;15692}1569315694// For a class type with a virtual destructor, the selected operator delete15695// is the one looked up when building the destructor.15696if (!E->isArrayForm() && !E->isGlobalDelete()) {15697const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);15698if (VirtualDelete &&15699!VirtualDelete->isReplaceableGlobalAllocationFunction()) {15700Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)15701<< isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;15702return false;15703}15704}1570515706if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),15707(*Alloc)->Value, AllocType))15708return false;1570915710if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {15711// The element was already erased. This means the destructor call also15712// deleted the object.15713// FIXME: This probably results in undefined behavior before we get this15714// far, and should be diagnosed elsewhere first.15715Info.FFDiag(E, diag::note_constexpr_double_delete);15716return false;15717}1571815719return true;15720}1572115722static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {15723assert(!E->isValueDependent());15724assert(E->isPRValue() && E->getType()->isVoidType());15725return VoidExprEvaluator(Info).Visit(E);15726}1572715728//===----------------------------------------------------------------------===//15729// Top level Expr::EvaluateAsRValue method.15730//===----------------------------------------------------------------------===//1573115732static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {15733assert(!E->isValueDependent());15734// In C, function designators are not lvalues, but we evaluate them as if they15735// are.15736QualType T = E->getType();15737if (E->isGLValue() || T->isFunctionType()) {15738LValue LV;15739if (!EvaluateLValue(E, LV, Info))15740return false;15741LV.moveInto(Result);15742} else if (T->isVectorType()) {15743if (!EvaluateVector(E, Result, Info))15744return false;15745} else if (T->isIntegralOrEnumerationType()) {15746if (!IntExprEvaluator(Info, Result).Visit(E))15747return false;15748} else if (T->hasPointerRepresentation()) {15749LValue LV;15750if (!EvaluatePointer(E, LV, Info))15751return false;15752LV.moveInto(Result);15753} else if (T->isRealFloatingType()) {15754llvm::APFloat F(0.0);15755if (!EvaluateFloat(E, F, Info))15756return false;15757Result = APValue(F);15758} else if (T->isAnyComplexType()) {15759ComplexValue C;15760if (!EvaluateComplex(E, C, Info))15761return false;15762C.moveInto(Result);15763} else if (T->isFixedPointType()) {15764if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;15765} else if (T->isMemberPointerType()) {15766MemberPtr P;15767if (!EvaluateMemberPointer(E, P, Info))15768return false;15769P.moveInto(Result);15770return true;15771} else if (T->isArrayType()) {15772LValue LV;15773APValue &Value =15774Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);15775if (!EvaluateArray(E, LV, Value, Info))15776return false;15777Result = Value;15778} else if (T->isRecordType()) {15779LValue LV;15780APValue &Value =15781Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);15782if (!EvaluateRecord(E, LV, Value, Info))15783return false;15784Result = Value;15785} else if (T->isVoidType()) {15786if (!Info.getLangOpts().CPlusPlus11)15787Info.CCEDiag(E, diag::note_constexpr_nonliteral)15788<< E->getType();15789if (!EvaluateVoid(E, Info))15790return false;15791} else if (T->isAtomicType()) {15792QualType Unqual = T.getAtomicUnqualifiedType();15793if (Unqual->isArrayType() || Unqual->isRecordType()) {15794LValue LV;15795APValue &Value = Info.CurrentCall->createTemporary(15796E, Unqual, ScopeKind::FullExpression, LV);15797if (!EvaluateAtomic(E, &LV, Value, Info))15798return false;15799Result = Value;15800} else {15801if (!EvaluateAtomic(E, nullptr, Result, Info))15802return false;15803}15804} else if (Info.getLangOpts().CPlusPlus11) {15805Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();15806return false;15807} else {15808Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);15809return false;15810}1581115812return true;15813}1581415815/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some15816/// cases, the in-place evaluation is essential, since later initializers for15817/// an object can indirectly refer to subobjects which were initialized earlier.15818static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,15819const Expr *E, bool AllowNonLiteralTypes) {15820assert(!E->isValueDependent());1582115822if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))15823return false;1582415825if (E->isPRValue()) {15826// Evaluate arrays and record types in-place, so that later initializers can15827// refer to earlier-initialized members of the object.15828QualType T = E->getType();15829if (T->isArrayType())15830return EvaluateArray(E, This, Result, Info);15831else if (T->isRecordType())15832return EvaluateRecord(E, This, Result, Info);15833else if (T->isAtomicType()) {15834QualType Unqual = T.getAtomicUnqualifiedType();15835if (Unqual->isArrayType() || Unqual->isRecordType())15836return EvaluateAtomic(E, &This, Result, Info);15837}15838}1583915840// For any other type, in-place evaluation is unimportant.15841return Evaluate(Result, Info, E);15842}1584315844/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit15845/// lvalue-to-rvalue cast if it is an lvalue.15846static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {15847assert(!E->isValueDependent());1584815849if (E->getType().isNull())15850return false;1585115852if (!CheckLiteralType(Info, E))15853return false;1585415855if (Info.EnableNewConstInterp) {15856if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))15857return false;15858return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,15859ConstantExprKind::Normal);15860}1586115862if (!::Evaluate(Result, Info, E))15863return false;1586415865// Implicit lvalue-to-rvalue cast.15866if (E->isGLValue()) {15867LValue LV;15868LV.setFrom(Info.Ctx, Result);15869if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))15870return false;15871}1587215873// Check this core constant expression is a constant expression.15874return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,15875ConstantExprKind::Normal) &&15876CheckMemoryLeaks(Info);15877}1587815879static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,15880const ASTContext &Ctx, bool &IsConst) {15881// Fast-path evaluations of integer literals, since we sometimes see files15882// containing vast quantities of these.15883if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {15884Result.Val = APValue(APSInt(L->getValue(),15885L->getType()->isUnsignedIntegerType()));15886IsConst = true;15887return true;15888}1588915890if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {15891Result.Val = APValue(APSInt(APInt(1, L->getValue())));15892IsConst = true;15893return true;15894}1589515896if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {15897if (CE->hasAPValueResult()) {15898APValue APV = CE->getAPValueResult();15899if (!APV.isLValue()) {15900Result.Val = std::move(APV);15901IsConst = true;15902return true;15903}15904}1590515906// The SubExpr is usually just an IntegerLiteral.15907return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);15908}1590915910// This case should be rare, but we need to check it before we check on15911// the type below.15912if (Exp->getType().isNull()) {15913IsConst = false;15914return true;15915}1591615917return false;15918}1591915920static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,15921Expr::SideEffectsKind SEK) {15922return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||15923(SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);15924}1592515926static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,15927const ASTContext &Ctx, EvalInfo &Info) {15928assert(!E->isValueDependent());15929bool IsConst;15930if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))15931return IsConst;1593215933return EvaluateAsRValue(Info, E, Result.Val);15934}1593515936static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,15937const ASTContext &Ctx,15938Expr::SideEffectsKind AllowSideEffects,15939EvalInfo &Info) {15940assert(!E->isValueDependent());15941if (!E->getType()->isIntegralOrEnumerationType())15942return false;1594315944if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||15945!ExprResult.Val.isInt() ||15946hasUnacceptableSideEffect(ExprResult, AllowSideEffects))15947return false;1594815949return true;15950}1595115952static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,15953const ASTContext &Ctx,15954Expr::SideEffectsKind AllowSideEffects,15955EvalInfo &Info) {15956assert(!E->isValueDependent());15957if (!E->getType()->isFixedPointType())15958return false;1595915960if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))15961return false;1596215963if (!ExprResult.Val.isFixedPoint() ||15964hasUnacceptableSideEffect(ExprResult, AllowSideEffects))15965return false;1596615967return true;15968}1596915970/// EvaluateAsRValue - Return true if this is a constant which we can fold using15971/// any crazy technique (that has nothing to do with language standards) that15972/// we want to. If this function returns true, it returns the folded constant15973/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion15974/// will be applied to the result.15975bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,15976bool InConstantContext) const {15977assert(!isValueDependent() &&15978"Expression evaluator can't be called on a dependent expression.");15979ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");15980EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);15981Info.InConstantContext = InConstantContext;15982return ::EvaluateAsRValue(this, Result, Ctx, Info);15983}1598415985bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,15986bool InConstantContext) const {15987assert(!isValueDependent() &&15988"Expression evaluator can't be called on a dependent expression.");15989ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");15990EvalResult Scratch;15991return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&15992HandleConversionToBool(Scratch.Val, Result);15993}1599415995bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,15996SideEffectsKind AllowSideEffects,15997bool InConstantContext) const {15998assert(!isValueDependent() &&15999"Expression evaluator can't be called on a dependent expression.");16000ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");16001EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);16002Info.InConstantContext = InConstantContext;16003return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);16004}1600516006bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,16007SideEffectsKind AllowSideEffects,16008bool InConstantContext) const {16009assert(!isValueDependent() &&16010"Expression evaluator can't be called on a dependent expression.");16011ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");16012EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);16013Info.InConstantContext = InConstantContext;16014return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);16015}1601616017bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,16018SideEffectsKind AllowSideEffects,16019bool InConstantContext) const {16020assert(!isValueDependent() &&16021"Expression evaluator can't be called on a dependent expression.");1602216023if (!getType()->isRealFloatingType())16024return false;1602516026ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");16027EvalResult ExprResult;16028if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||16029!ExprResult.Val.isFloat() ||16030hasUnacceptableSideEffect(ExprResult, AllowSideEffects))16031return false;1603216033Result = ExprResult.Val.getFloat();16034return true;16035}1603616037bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,16038bool InConstantContext) const {16039assert(!isValueDependent() &&16040"Expression evaluator can't be called on a dependent expression.");1604116042ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");16043EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);16044Info.InConstantContext = InConstantContext;16045LValue LV;16046CheckedTemporaries CheckedTemps;16047if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||16048Result.HasSideEffects ||16049!CheckLValueConstantExpression(Info, getExprLoc(),16050Ctx.getLValueReferenceType(getType()), LV,16051ConstantExprKind::Normal, CheckedTemps))16052return false;1605316054LV.moveInto(Result.Val);16055return true;16056}1605716058static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,16059APValue DestroyedValue, QualType Type,16060SourceLocation Loc, Expr::EvalStatus &EStatus,16061bool IsConstantDestruction) {16062EvalInfo Info(Ctx, EStatus,16063IsConstantDestruction ? EvalInfo::EM_ConstantExpression16064: EvalInfo::EM_ConstantFold);16065Info.setEvaluatingDecl(Base, DestroyedValue,16066EvalInfo::EvaluatingDeclKind::Dtor);16067Info.InConstantContext = IsConstantDestruction;1606816069LValue LVal;16070LVal.set(Base);1607116072if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||16073EStatus.HasSideEffects)16074return false;1607516076if (!Info.discardCleanups())16077llvm_unreachable("Unhandled cleanup; missing full expression marker?");1607816079return true;16080}1608116082bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,16083ConstantExprKind Kind) const {16084assert(!isValueDependent() &&16085"Expression evaluator can't be called on a dependent expression.");16086bool IsConst;16087if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())16088return true;1608916090ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");16091EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;16092EvalInfo Info(Ctx, Result, EM);16093Info.InConstantContext = true;1609416095if (Info.EnableNewConstInterp) {16096if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val))16097return false;16098return CheckConstantExpression(Info, getExprLoc(),16099getStorageType(Ctx, this), Result.Val, Kind);16100}1610116102// The type of the object we're initializing is 'const T' for a class NTTP.16103QualType T = getType();16104if (Kind == ConstantExprKind::ClassTemplateArgument)16105T.addConst();1610616107// If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to16108// represent the result of the evaluation. CheckConstantExpression ensures16109// this doesn't escape.16110MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);16111APValue::LValueBase Base(&BaseMTE);16112Info.setEvaluatingDecl(Base, Result.Val);1611316114if (Info.EnableNewConstInterp) {16115if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))16116return false;16117} else {16118LValue LVal;16119LVal.set(Base);16120// C++23 [intro.execution]/p516121// A full-expression is [...] a constant-expression16122// So we need to make sure temporary objects are destroyed after having16123// evaluating the expression (per C++23 [class.temporary]/p4).16124FullExpressionRAII Scope(Info);16125if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||16126Result.HasSideEffects || !Scope.destroy())16127return false;1612816129if (!Info.discardCleanups())16130llvm_unreachable("Unhandled cleanup; missing full expression marker?");16131}1613216133if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),16134Result.Val, Kind))16135return false;16136if (!CheckMemoryLeaks(Info))16137return false;1613816139// If this is a class template argument, it's required to have constant16140// destruction too.16141if (Kind == ConstantExprKind::ClassTemplateArgument &&16142(!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,16143true) ||16144Result.HasSideEffects)) {16145// FIXME: Prefix a note to indicate that the problem is lack of constant16146// destruction.16147return false;16148}1614916150return true;16151}1615216153bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,16154const VarDecl *VD,16155SmallVectorImpl<PartialDiagnosticAt> &Notes,16156bool IsConstantInitialization) const {16157assert(!isValueDependent() &&16158"Expression evaluator can't be called on a dependent expression.");1615916160llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {16161std::string Name;16162llvm::raw_string_ostream OS(Name);16163VD->printQualifiedName(OS);16164return Name;16165});1616616167Expr::EvalStatus EStatus;16168EStatus.Diag = &Notes;1616916170EvalInfo Info(Ctx, EStatus,16171(IsConstantInitialization &&16172(Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))16173? EvalInfo::EM_ConstantExpression16174: EvalInfo::EM_ConstantFold);16175Info.setEvaluatingDecl(VD, Value);16176Info.InConstantContext = IsConstantInitialization;1617716178SourceLocation DeclLoc = VD->getLocation();16179QualType DeclTy = VD->getType();1618016181if (Info.EnableNewConstInterp) {16182auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();16183if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))16184return false;1618516186return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,16187ConstantExprKind::Normal);16188} else {16189LValue LVal;16190LVal.set(VD);1619116192{16193// C++23 [intro.execution]/p516194// A full-expression is ... an init-declarator ([dcl.decl]) or a16195// mem-initializer.16196// So we need to make sure temporary objects are destroyed after having16197// evaluated the expression (per C++23 [class.temporary]/p4).16198//16199// FIXME: Otherwise this may break test/Modules/pr68702.cpp because the16200// serialization code calls ParmVarDecl::getDefaultArg() which strips the16201// outermost FullExpr, such as ExprWithCleanups.16202FullExpressionRAII Scope(Info);16203if (!EvaluateInPlace(Value, Info, LVal, this,16204/*AllowNonLiteralTypes=*/true) ||16205EStatus.HasSideEffects)16206return false;16207}1620816209// At this point, any lifetime-extended temporaries are completely16210// initialized.16211Info.performLifetimeExtension();1621216213if (!Info.discardCleanups())16214llvm_unreachable("Unhandled cleanup; missing full expression marker?");16215}1621616217return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,16218ConstantExprKind::Normal) &&16219CheckMemoryLeaks(Info);16220}1622116222bool VarDecl::evaluateDestruction(16223SmallVectorImpl<PartialDiagnosticAt> &Notes) const {16224Expr::EvalStatus EStatus;16225EStatus.Diag = &Notes;1622616227// Only treat the destruction as constant destruction if we formally have16228// constant initialization (or are usable in a constant expression).16229bool IsConstantDestruction = hasConstantInitialization();1623016231// Make a copy of the value for the destructor to mutate, if we know it.16232// Otherwise, treat the value as default-initialized; if the destructor works16233// anyway, then the destruction is constant (and must be essentially empty).16234APValue DestroyedValue;16235if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())16236DestroyedValue = *getEvaluatedValue();16237else if (!handleDefaultInitValue(getType(), DestroyedValue))16238return false;1623916240if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),16241getType(), getLocation(), EStatus,16242IsConstantDestruction) ||16243EStatus.HasSideEffects)16244return false;1624516246ensureEvaluatedStmt()->HasConstantDestruction = true;16247return true;16248}1624916250/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be16251/// constant folded, but discard the result.16252bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {16253assert(!isValueDependent() &&16254"Expression evaluator can't be called on a dependent expression.");1625516256EvalResult Result;16257return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&16258!hasUnacceptableSideEffect(Result, SEK);16259}1626016261APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,16262SmallVectorImpl<PartialDiagnosticAt> *Diag) const {16263assert(!isValueDependent() &&16264"Expression evaluator can't be called on a dependent expression.");1626516266ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");16267EvalResult EVResult;16268EVResult.Diag = Diag;16269EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);16270Info.InConstantContext = true;1627116272bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);16273(void)Result;16274assert(Result && "Could not evaluate expression");16275assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");1627616277return EVResult.Val.getInt();16278}1627916280APSInt Expr::EvaluateKnownConstIntCheckOverflow(16281const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {16282assert(!isValueDependent() &&16283"Expression evaluator can't be called on a dependent expression.");1628416285ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");16286EvalResult EVResult;16287EVResult.Diag = Diag;16288EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);16289Info.InConstantContext = true;16290Info.CheckingForUndefinedBehavior = true;1629116292bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);16293(void)Result;16294assert(Result && "Could not evaluate expression");16295assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");1629616297return EVResult.Val.getInt();16298}1629916300void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {16301assert(!isValueDependent() &&16302"Expression evaluator can't be called on a dependent expression.");1630316304ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");16305bool IsConst;16306EvalResult EVResult;16307if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {16308EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);16309Info.CheckingForUndefinedBehavior = true;16310(void)::EvaluateAsRValue(Info, this, EVResult.Val);16311}16312}1631316314bool Expr::EvalResult::isGlobalLValue() const {16315assert(Val.isLValue());16316return IsGlobalLValue(Val.getLValueBase());16317}1631816319/// isIntegerConstantExpr - this recursive routine will test if an expression is16320/// an integer constant expression.1632116322/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,16323/// comma, etc1632416325// CheckICE - This function does the fundamental ICE checking: the returned16326// ICEDiag contains an ICEKind indicating whether the expression is an ICE,16327// and a (possibly null) SourceLocation indicating the location of the problem.16328//16329// Note that to reduce code duplication, this helper does no evaluation16330// itself; the caller checks whether the expression is evaluatable, and16331// in the rare cases where CheckICE actually cares about the evaluated16332// value, it calls into Evaluate.1633316334namespace {1633516336enum ICEKind {16337/// This expression is an ICE.16338IK_ICE,16339/// This expression is not an ICE, but if it isn't evaluated, it's16340/// a legal subexpression for an ICE. This return value is used to handle16341/// the comma operator in C99 mode, and non-constant subexpressions.16342IK_ICEIfUnevaluated,16343/// This expression is not an ICE, and is not a legal subexpression for one.16344IK_NotICE16345};1634616347struct ICEDiag {16348ICEKind Kind;16349SourceLocation Loc;1635016351ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}16352};1635316354}1635516356static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }1635716358static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }1635916360static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {16361Expr::EvalResult EVResult;16362Expr::EvalStatus Status;16363EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);1636416365Info.InConstantContext = true;16366if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||16367!EVResult.Val.isInt())16368return ICEDiag(IK_NotICE, E->getBeginLoc());1636916370return NoDiag();16371}1637216373static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {16374assert(!E->isValueDependent() && "Should not see value dependent exprs!");16375if (!E->getType()->isIntegralOrEnumerationType())16376return ICEDiag(IK_NotICE, E->getBeginLoc());1637716378switch (E->getStmtClass()) {16379#define ABSTRACT_STMT(Node)16380#define STMT(Node, Base) case Expr::Node##Class:16381#define EXPR(Node, Base)16382#include "clang/AST/StmtNodes.inc"16383case Expr::PredefinedExprClass:16384case Expr::FloatingLiteralClass:16385case Expr::ImaginaryLiteralClass:16386case Expr::StringLiteralClass:16387case Expr::ArraySubscriptExprClass:16388case Expr::MatrixSubscriptExprClass:16389case Expr::ArraySectionExprClass:16390case Expr::OMPArrayShapingExprClass:16391case Expr::OMPIteratorExprClass:16392case Expr::MemberExprClass:16393case Expr::CompoundAssignOperatorClass:16394case Expr::CompoundLiteralExprClass:16395case Expr::ExtVectorElementExprClass:16396case Expr::DesignatedInitExprClass:16397case Expr::ArrayInitLoopExprClass:16398case Expr::ArrayInitIndexExprClass:16399case Expr::NoInitExprClass:16400case Expr::DesignatedInitUpdateExprClass:16401case Expr::ImplicitValueInitExprClass:16402case Expr::ParenListExprClass:16403case Expr::VAArgExprClass:16404case Expr::AddrLabelExprClass:16405case Expr::StmtExprClass:16406case Expr::CXXMemberCallExprClass:16407case Expr::CUDAKernelCallExprClass:16408case Expr::CXXAddrspaceCastExprClass:16409case Expr::CXXDynamicCastExprClass:16410case Expr::CXXTypeidExprClass:16411case Expr::CXXUuidofExprClass:16412case Expr::MSPropertyRefExprClass:16413case Expr::MSPropertySubscriptExprClass:16414case Expr::CXXNullPtrLiteralExprClass:16415case Expr::UserDefinedLiteralClass:16416case Expr::CXXThisExprClass:16417case Expr::CXXThrowExprClass:16418case Expr::CXXNewExprClass:16419case Expr::CXXDeleteExprClass:16420case Expr::CXXPseudoDestructorExprClass:16421case Expr::UnresolvedLookupExprClass:16422case Expr::TypoExprClass:16423case Expr::RecoveryExprClass:16424case Expr::DependentScopeDeclRefExprClass:16425case Expr::CXXConstructExprClass:16426case Expr::CXXInheritedCtorInitExprClass:16427case Expr::CXXStdInitializerListExprClass:16428case Expr::CXXBindTemporaryExprClass:16429case Expr::ExprWithCleanupsClass:16430case Expr::CXXTemporaryObjectExprClass:16431case Expr::CXXUnresolvedConstructExprClass:16432case Expr::CXXDependentScopeMemberExprClass:16433case Expr::UnresolvedMemberExprClass:16434case Expr::ObjCStringLiteralClass:16435case Expr::ObjCBoxedExprClass:16436case Expr::ObjCArrayLiteralClass:16437case Expr::ObjCDictionaryLiteralClass:16438case Expr::ObjCEncodeExprClass:16439case Expr::ObjCMessageExprClass:16440case Expr::ObjCSelectorExprClass:16441case Expr::ObjCProtocolExprClass:16442case Expr::ObjCIvarRefExprClass:16443case Expr::ObjCPropertyRefExprClass:16444case Expr::ObjCSubscriptRefExprClass:16445case Expr::ObjCIsaExprClass:16446case Expr::ObjCAvailabilityCheckExprClass:16447case Expr::ShuffleVectorExprClass:16448case Expr::ConvertVectorExprClass:16449case Expr::BlockExprClass:16450case Expr::NoStmtClass:16451case Expr::OpaqueValueExprClass:16452case Expr::PackExpansionExprClass:16453case Expr::SubstNonTypeTemplateParmPackExprClass:16454case Expr::FunctionParmPackExprClass:16455case Expr::AsTypeExprClass:16456case Expr::ObjCIndirectCopyRestoreExprClass:16457case Expr::MaterializeTemporaryExprClass:16458case Expr::PseudoObjectExprClass:16459case Expr::AtomicExprClass:16460case Expr::LambdaExprClass:16461case Expr::CXXFoldExprClass:16462case Expr::CoawaitExprClass:16463case Expr::DependentCoawaitExprClass:16464case Expr::CoyieldExprClass:16465case Expr::SYCLUniqueStableNameExprClass:16466case Expr::CXXParenListInitExprClass:16467return ICEDiag(IK_NotICE, E->getBeginLoc());1646816469case Expr::InitListExprClass: {16470// C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the16471// form "T x = { a };" is equivalent to "T x = a;".16472// Unless we're initializing a reference, T is a scalar as it is known to be16473// of integral or enumeration type.16474if (E->isPRValue())16475if (cast<InitListExpr>(E)->getNumInits() == 1)16476return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);16477return ICEDiag(IK_NotICE, E->getBeginLoc());16478}1647916480case Expr::SizeOfPackExprClass:16481case Expr::GNUNullExprClass:16482case Expr::SourceLocExprClass:16483case Expr::EmbedExprClass:16484return NoDiag();1648516486case Expr::PackIndexingExprClass:16487return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);1648816489case Expr::SubstNonTypeTemplateParmExprClass:16490return16491CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);1649216493case Expr::ConstantExprClass:16494return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);1649516496case Expr::ParenExprClass:16497return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);16498case Expr::GenericSelectionExprClass:16499return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);16500case Expr::IntegerLiteralClass:16501case Expr::FixedPointLiteralClass:16502case Expr::CharacterLiteralClass:16503case Expr::ObjCBoolLiteralExprClass:16504case Expr::CXXBoolLiteralExprClass:16505case Expr::CXXScalarValueInitExprClass:16506case Expr::TypeTraitExprClass:16507case Expr::ConceptSpecializationExprClass:16508case Expr::RequiresExprClass:16509case Expr::ArrayTypeTraitExprClass:16510case Expr::ExpressionTraitExprClass:16511case Expr::CXXNoexceptExprClass:16512return NoDiag();16513case Expr::CallExprClass:16514case Expr::CXXOperatorCallExprClass: {16515// C99 6.6/3 allows function calls within unevaluated subexpressions of16516// constant expressions, but they can never be ICEs because an ICE cannot16517// contain an operand of (pointer to) function type.16518const CallExpr *CE = cast<CallExpr>(E);16519if (CE->getBuiltinCallee())16520return CheckEvalInICE(E, Ctx);16521return ICEDiag(IK_NotICE, E->getBeginLoc());16522}16523case Expr::CXXRewrittenBinaryOperatorClass:16524return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),16525Ctx);16526case Expr::DeclRefExprClass: {16527const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();16528if (isa<EnumConstantDecl>(D))16529return NoDiag();1653016531// C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified16532// integer variables in constant expressions:16533//16534// C++ 7.1.5.1p216535// A variable of non-volatile const-qualified integral or enumeration16536// type initialized by an ICE can be used in ICEs.16537//16538// We sometimes use CheckICE to check the C++98 rules in C++11 mode. In16539// that mode, use of reference variables should not be allowed.16540const VarDecl *VD = dyn_cast<VarDecl>(D);16541if (VD && VD->isUsableInConstantExpressions(Ctx) &&16542!VD->getType()->isReferenceType())16543return NoDiag();1654416545return ICEDiag(IK_NotICE, E->getBeginLoc());16546}16547case Expr::UnaryOperatorClass: {16548const UnaryOperator *Exp = cast<UnaryOperator>(E);16549switch (Exp->getOpcode()) {16550case UO_PostInc:16551case UO_PostDec:16552case UO_PreInc:16553case UO_PreDec:16554case UO_AddrOf:16555case UO_Deref:16556case UO_Coawait:16557// C99 6.6/3 allows increment and decrement within unevaluated16558// subexpressions of constant expressions, but they can never be ICEs16559// because an ICE cannot contain an lvalue operand.16560return ICEDiag(IK_NotICE, E->getBeginLoc());16561case UO_Extension:16562case UO_LNot:16563case UO_Plus:16564case UO_Minus:16565case UO_Not:16566case UO_Real:16567case UO_Imag:16568return CheckICE(Exp->getSubExpr(), Ctx);16569}16570llvm_unreachable("invalid unary operator class");16571}16572case Expr::OffsetOfExprClass: {16573// Note that per C99, offsetof must be an ICE. And AFAIK, using16574// EvaluateAsRValue matches the proposed gcc behavior for cases like16575// "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect16576// compliance: we should warn earlier for offsetof expressions with16577// array subscripts that aren't ICEs, and if the array subscripts16578// are ICEs, the value of the offsetof must be an integer constant.16579return CheckEvalInICE(E, Ctx);16580}16581case Expr::UnaryExprOrTypeTraitExprClass: {16582const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);16583if ((Exp->getKind() == UETT_SizeOf) &&16584Exp->getTypeOfArgument()->isVariableArrayType())16585return ICEDiag(IK_NotICE, E->getBeginLoc());16586return NoDiag();16587}16588case Expr::BinaryOperatorClass: {16589const BinaryOperator *Exp = cast<BinaryOperator>(E);16590switch (Exp->getOpcode()) {16591case BO_PtrMemD:16592case BO_PtrMemI:16593case BO_Assign:16594case BO_MulAssign:16595case BO_DivAssign:16596case BO_RemAssign:16597case BO_AddAssign:16598case BO_SubAssign:16599case BO_ShlAssign:16600case BO_ShrAssign:16601case BO_AndAssign:16602case BO_XorAssign:16603case BO_OrAssign:16604// C99 6.6/3 allows assignments within unevaluated subexpressions of16605// constant expressions, but they can never be ICEs because an ICE cannot16606// contain an lvalue operand.16607return ICEDiag(IK_NotICE, E->getBeginLoc());1660816609case BO_Mul:16610case BO_Div:16611case BO_Rem:16612case BO_Add:16613case BO_Sub:16614case BO_Shl:16615case BO_Shr:16616case BO_LT:16617case BO_GT:16618case BO_LE:16619case BO_GE:16620case BO_EQ:16621case BO_NE:16622case BO_And:16623case BO_Xor:16624case BO_Or:16625case BO_Comma:16626case BO_Cmp: {16627ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);16628ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);16629if (Exp->getOpcode() == BO_Div ||16630Exp->getOpcode() == BO_Rem) {16631// EvaluateAsRValue gives an error for undefined Div/Rem, so make sure16632// we don't evaluate one.16633if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {16634llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);16635if (REval == 0)16636return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());16637if (REval.isSigned() && REval.isAllOnes()) {16638llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);16639if (LEval.isMinSignedValue())16640return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());16641}16642}16643}16644if (Exp->getOpcode() == BO_Comma) {16645if (Ctx.getLangOpts().C99) {16646// C99 6.6p3 introduces a strange edge case: comma can be in an ICE16647// if it isn't evaluated.16648if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)16649return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());16650} else {16651// In both C89 and C++, commas in ICEs are illegal.16652return ICEDiag(IK_NotICE, E->getBeginLoc());16653}16654}16655return Worst(LHSResult, RHSResult);16656}16657case BO_LAnd:16658case BO_LOr: {16659ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);16660ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);16661if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {16662// Rare case where the RHS has a comma "side-effect"; we need16663// to actually check the condition to see whether the side16664// with the comma is evaluated.16665if ((Exp->getOpcode() == BO_LAnd) !=16666(Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))16667return RHSResult;16668return NoDiag();16669}1667016671return Worst(LHSResult, RHSResult);16672}16673}16674llvm_unreachable("invalid binary operator kind");16675}16676case Expr::ImplicitCastExprClass:16677case Expr::CStyleCastExprClass:16678case Expr::CXXFunctionalCastExprClass:16679case Expr::CXXStaticCastExprClass:16680case Expr::CXXReinterpretCastExprClass:16681case Expr::CXXConstCastExprClass:16682case Expr::ObjCBridgedCastExprClass: {16683const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();16684if (isa<ExplicitCastExpr>(E)) {16685if (const FloatingLiteral *FL16686= dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {16687unsigned DestWidth = Ctx.getIntWidth(E->getType());16688bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();16689APSInt IgnoredVal(DestWidth, !DestSigned);16690bool Ignored;16691// If the value does not fit in the destination type, the behavior is16692// undefined, so we are not required to treat it as a constant16693// expression.16694if (FL->getValue().convertToInteger(IgnoredVal,16695llvm::APFloat::rmTowardZero,16696&Ignored) & APFloat::opInvalidOp)16697return ICEDiag(IK_NotICE, E->getBeginLoc());16698return NoDiag();16699}16700}16701switch (cast<CastExpr>(E)->getCastKind()) {16702case CK_LValueToRValue:16703case CK_AtomicToNonAtomic:16704case CK_NonAtomicToAtomic:16705case CK_NoOp:16706case CK_IntegralToBoolean:16707case CK_IntegralCast:16708return CheckICE(SubExpr, Ctx);16709default:16710return ICEDiag(IK_NotICE, E->getBeginLoc());16711}16712}16713case Expr::BinaryConditionalOperatorClass: {16714const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);16715ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);16716if (CommonResult.Kind == IK_NotICE) return CommonResult;16717ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);16718if (FalseResult.Kind == IK_NotICE) return FalseResult;16719if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;16720if (FalseResult.Kind == IK_ICEIfUnevaluated &&16721Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();16722return FalseResult;16723}16724case Expr::ConditionalOperatorClass: {16725const ConditionalOperator *Exp = cast<ConditionalOperator>(E);16726// If the condition (ignoring parens) is a __builtin_constant_p call,16727// then only the true side is actually considered in an integer constant16728// expression, and it is fully evaluated. This is an important GNU16729// extension. See GCC PR38377 for discussion.16730if (const CallExpr *CallCE16731= dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))16732if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)16733return CheckEvalInICE(E, Ctx);16734ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);16735if (CondResult.Kind == IK_NotICE)16736return CondResult;1673716738ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);16739ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);1674016741if (TrueResult.Kind == IK_NotICE)16742return TrueResult;16743if (FalseResult.Kind == IK_NotICE)16744return FalseResult;16745if (CondResult.Kind == IK_ICEIfUnevaluated)16746return CondResult;16747if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)16748return NoDiag();16749// Rare case where the diagnostics depend on which side is evaluated16750// Note that if we get here, CondResult is 0, and at least one of16751// TrueResult and FalseResult is non-zero.16752if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)16753return FalseResult;16754return TrueResult;16755}16756case Expr::CXXDefaultArgExprClass:16757return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);16758case Expr::CXXDefaultInitExprClass:16759return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);16760case Expr::ChooseExprClass: {16761return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);16762}16763case Expr::BuiltinBitCastExprClass: {16764if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))16765return ICEDiag(IK_NotICE, E->getBeginLoc());16766return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);16767}16768}1676916770llvm_unreachable("Invalid StmtClass!");16771}1677216773/// Evaluate an expression as a C++11 integral constant expression.16774static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,16775const Expr *E,16776llvm::APSInt *Value,16777SourceLocation *Loc) {16778if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {16779if (Loc) *Loc = E->getExprLoc();16780return false;16781}1678216783APValue Result;16784if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))16785return false;1678616787if (!Result.isInt()) {16788if (Loc) *Loc = E->getExprLoc();16789return false;16790}1679116792if (Value) *Value = Result.getInt();16793return true;16794}1679516796bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,16797SourceLocation *Loc) const {16798assert(!isValueDependent() &&16799"Expression evaluator can't be called on a dependent expression.");1680016801ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");1680216803if (Ctx.getLangOpts().CPlusPlus11)16804return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);1680516806ICEDiag D = CheckICE(this, Ctx);16807if (D.Kind != IK_ICE) {16808if (Loc) *Loc = D.Loc;16809return false;16810}16811return true;16812}1681316814std::optional<llvm::APSInt>16815Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {16816if (isValueDependent()) {16817// Expression evaluator can't succeed on a dependent expression.16818return std::nullopt;16819}1682016821APSInt Value;1682216823if (Ctx.getLangOpts().CPlusPlus11) {16824if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))16825return Value;16826return std::nullopt;16827}1682816829if (!isIntegerConstantExpr(Ctx, Loc))16830return std::nullopt;1683116832// The only possible side-effects here are due to UB discovered in the16833// evaluation (for instance, INT_MAX + 1). In such a case, we are still16834// required to treat the expression as an ICE, so we produce the folded16835// value.16836EvalResult ExprResult;16837Expr::EvalStatus Status;16838EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);16839Info.InConstantContext = true;1684016841if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))16842llvm_unreachable("ICE cannot be evaluated!");1684316844return ExprResult.Val.getInt();16845}1684616847bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {16848assert(!isValueDependent() &&16849"Expression evaluator can't be called on a dependent expression.");1685016851return CheckICE(this, Ctx).Kind == IK_ICE;16852}1685316854bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,16855SourceLocation *Loc) const {16856assert(!isValueDependent() &&16857"Expression evaluator can't be called on a dependent expression.");1685816859// We support this checking in C++98 mode in order to diagnose compatibility16860// issues.16861assert(Ctx.getLangOpts().CPlusPlus);1686216863// Build evaluation settings.16864Expr::EvalStatus Status;16865SmallVector<PartialDiagnosticAt, 8> Diags;16866Status.Diag = &Diags;16867EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);1686816869APValue Scratch;16870bool IsConstExpr =16871::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&16872// FIXME: We don't produce a diagnostic for this, but the callers that16873// call us on arbitrary full-expressions should generally not care.16874Info.discardCleanups() && !Status.HasSideEffects;1687516876if (!Diags.empty()) {16877IsConstExpr = false;16878if (Loc) *Loc = Diags[0].first;16879} else if (!IsConstExpr) {16880// FIXME: This shouldn't happen.16881if (Loc) *Loc = getExprLoc();16882}1688316884return IsConstExpr;16885}1688616887bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,16888const FunctionDecl *Callee,16889ArrayRef<const Expr*> Args,16890const Expr *This) const {16891assert(!isValueDependent() &&16892"Expression evaluator can't be called on a dependent expression.");1689316894llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {16895std::string Name;16896llvm::raw_string_ostream OS(Name);16897Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),16898/*Qualified=*/true);16899return Name;16900});1690116902Expr::EvalStatus Status;16903EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);16904Info.InConstantContext = true;1690516906LValue ThisVal;16907const LValue *ThisPtr = nullptr;16908if (This) {16909#ifndef NDEBUG16910auto *MD = dyn_cast<CXXMethodDecl>(Callee);16911assert(MD && "Don't provide `this` for non-methods.");16912assert(MD->isImplicitObjectMemberFunction() &&16913"Don't provide `this` for methods without an implicit object.");16914#endif16915if (!This->isValueDependent() &&16916EvaluateObjectArgument(Info, This, ThisVal) &&16917!Info.EvalStatus.HasSideEffects)16918ThisPtr = &ThisVal;1691916920// Ignore any side-effects from a failed evaluation. This is safe because16921// they can't interfere with any other argument evaluation.16922Info.EvalStatus.HasSideEffects = false;16923}1692416925CallRef Call = Info.CurrentCall->createCall(Callee);16926for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();16927I != E; ++I) {16928unsigned Idx = I - Args.begin();16929if (Idx >= Callee->getNumParams())16930break;16931const ParmVarDecl *PVD = Callee->getParamDecl(Idx);16932if ((*I)->isValueDependent() ||16933!EvaluateCallArg(PVD, *I, Call, Info) ||16934Info.EvalStatus.HasSideEffects) {16935// If evaluation fails, throw away the argument entirely.16936if (APValue *Slot = Info.getParamSlot(Call, PVD))16937*Slot = APValue();16938}1693916940// Ignore any side-effects from a failed evaluation. This is safe because16941// they can't interfere with any other argument evaluation.16942Info.EvalStatus.HasSideEffects = false;16943}1694416945// Parameter cleanups happen in the caller and are not part of this16946// evaluation.16947Info.discardCleanups();16948Info.EvalStatus.HasSideEffects = false;1694916950// Build fake call to Callee.16951CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,16952Call);16953// FIXME: Missing ExprWithCleanups in enable_if conditions?16954FullExpressionRAII Scope(Info);16955return Evaluate(Value, Info, this) && Scope.destroy() &&16956!Info.EvalStatus.HasSideEffects;16957}1695816959bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,16960SmallVectorImpl<16961PartialDiagnosticAt> &Diags) {16962// FIXME: It would be useful to check constexpr function templates, but at the16963// moment the constant expression evaluator cannot cope with the non-rigorous16964// ASTs which we build for dependent expressions.16965if (FD->isDependentContext())16966return true;1696716968llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {16969std::string Name;16970llvm::raw_string_ostream OS(Name);16971FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),16972/*Qualified=*/true);16973return Name;16974});1697516976Expr::EvalStatus Status;16977Status.Diag = &Diags;1697816979EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);16980Info.InConstantContext = true;16981Info.CheckingPotentialConstantExpression = true;1698216983// The constexpr VM attempts to compile all methods to bytecode here.16984if (Info.EnableNewConstInterp) {16985Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);16986return Diags.empty();16987}1698816989const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);16990const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;1699116992// Fabricate an arbitrary expression on the stack and pretend that it16993// is a temporary being used as the 'this' pointer.16994LValue This;16995ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);16996This.set({&VIE, Info.CurrentCall->Index});1699716998ArrayRef<const Expr*> Args;1699917000APValue Scratch;17001if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {17002// Evaluate the call as a constant initializer, to allow the construction17003// of objects of non-literal types.17004Info.setEvaluatingDecl(This.getLValueBase(), Scratch);17005HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);17006} else {17007SourceLocation Loc = FD->getLocation();17008HandleFunctionCall(17009Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,17010&VIE, Args, CallRef(), FD->getBody(), Info, Scratch,17011/*ResultSlot=*/nullptr);17012}1701317014return Diags.empty();17015}1701617017bool Expr::isPotentialConstantExprUnevaluated(Expr *E,17018const FunctionDecl *FD,17019SmallVectorImpl<17020PartialDiagnosticAt> &Diags) {17021assert(!E->isValueDependent() &&17022"Expression evaluator can't be called on a dependent expression.");1702317024Expr::EvalStatus Status;17025Status.Diag = &Diags;1702617027EvalInfo Info(FD->getASTContext(), Status,17028EvalInfo::EM_ConstantExpressionUnevaluated);17029Info.InConstantContext = true;17030Info.CheckingPotentialConstantExpression = true;1703117032// Fabricate a call stack frame to give the arguments a plausible cover story.17033CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,17034/*CallExpr=*/nullptr, CallRef());1703517036APValue ResultScratch;17037Evaluate(ResultScratch, Info, E);17038return Diags.empty();17039}1704017041bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,17042unsigned Type) const {17043if (!getType()->isPointerType())17044return false;1704517046Expr::EvalStatus Status;17047EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);17048return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);17049}1705017051static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,17052EvalInfo &Info, std::string *StringResult) {17053if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())17054return false;1705517056LValue String;1705717058if (!EvaluatePointer(E, String, Info))17059return false;1706017061QualType CharTy = E->getType()->getPointeeType();1706217063// Fast path: if it's a string literal, search the string value.17064if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(17065String.getLValueBase().dyn_cast<const Expr *>())) {17066StringRef Str = S->getBytes();17067int64_t Off = String.Offset.getQuantity();17068if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&17069S->getCharByteWidth() == 1 &&17070// FIXME: Add fast-path for wchar_t too.17071Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {17072Str = Str.substr(Off);1707317074StringRef::size_type Pos = Str.find(0);17075if (Pos != StringRef::npos)17076Str = Str.substr(0, Pos);1707717078Result = Str.size();17079if (StringResult)17080*StringResult = Str;17081return true;17082}1708317084// Fall through to slow path.17085}1708617087// Slow path: scan the bytes of the string looking for the terminating 0.17088for (uint64_t Strlen = 0; /**/; ++Strlen) {17089APValue Char;17090if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||17091!Char.isInt())17092return false;17093if (!Char.getInt()) {17094Result = Strlen;17095return true;17096} else if (StringResult)17097StringResult->push_back(Char.getInt().getExtValue());17098if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))17099return false;17100}17101}1710217103std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {17104Expr::EvalStatus Status;17105EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);17106uint64_t Result;17107std::string StringResult;1710817109if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))17110return StringResult;17111return {};17112}1711317114bool Expr::EvaluateCharRangeAsString(std::string &Result,17115const Expr *SizeExpression,17116const Expr *PtrExpression, ASTContext &Ctx,17117EvalResult &Status) const {17118LValue String;17119EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);17120Info.InConstantContext = true;1712117122FullExpressionRAII Scope(Info);17123APSInt SizeValue;17124if (!::EvaluateInteger(SizeExpression, SizeValue, Info))17125return false;1712617127uint64_t Size = SizeValue.getZExtValue();1712817129if (!::EvaluatePointer(PtrExpression, String, Info))17130return false;1713117132QualType CharTy = PtrExpression->getType()->getPointeeType();17133for (uint64_t I = 0; I < Size; ++I) {17134APValue Char;17135if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,17136Char))17137return false;1713817139APSInt C = Char.getInt();17140Result.push_back(static_cast<char>(C.getExtValue()));17141if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))17142return false;17143}17144if (!Scope.destroy())17145return false;1714617147if (!CheckMemoryLeaks(Info))17148return false;1714917150return true;17151}1715217153bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {17154Expr::EvalStatus Status;17155EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);17156return EvaluateBuiltinStrLen(this, Result, Info);17157}171581715917160