56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/TimeProfiler.h"
62#include "llvm/Support/raw_ostream.h"
67#define DEBUG_TYPE "exprconstant"
70using llvm::APFixedPoint;
74using llvm::FixedPointSemantics;
81 using SourceLocExprScopeGuard =
113 static const AllocSizeAttr *getAllocSizeAttr(
const CallExpr *CE) {
115 return DirectCallee->getAttr<AllocSizeAttr>();
117 return IndirectCallee->getAttr<AllocSizeAttr>();
125 static const CallExpr *tryUnwrapAllocSizeCall(
const Expr *E) {
133 if (
const auto *FE = dyn_cast<FullExpr>(E))
136 if (
const auto *Cast = dyn_cast<CastExpr>(E))
137 E = Cast->getSubExpr()->IgnoreParens();
139 if (
const auto *CE = dyn_cast<CallExpr>(E))
140 return getAllocSizeAttr(CE) ? CE :
nullptr;
147 const auto *E =
Base.dyn_cast<
const Expr *>();
148 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
156 case ConstantExprKind::Normal:
157 case ConstantExprKind::ClassTemplateArgument:
158 case ConstantExprKind::ImmediateInvocation:
163 case ConstantExprKind::NonClassTemplateArgument:
166 llvm_unreachable(
"unknown ConstantExprKind");
171 case ConstantExprKind::Normal:
172 case ConstantExprKind::ImmediateInvocation:
175 case ConstantExprKind::ClassTemplateArgument:
176 case ConstantExprKind::NonClassTemplateArgument:
179 llvm_unreachable(
"unknown ConstantExprKind");
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
196 bool &FirstEntryIsUnsizedArray) {
199 assert(!isBaseAnAllocSizeCall(
Base) &&
200 "Unsized arrays shouldn't appear here");
201 unsigned MostDerivedLength = 0;
204 for (
unsigned I = 0, N = Path.size(); I != N; ++I) {
208 MostDerivedLength = I + 1;
211 if (
auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
214 assert(I == 0 &&
"unexpected unsized array designator");
215 FirstEntryIsUnsizedArray =
true;
216 ArraySize = AssumedSizeForUnsizedArray;
222 MostDerivedLength = I + 1;
224 }
else if (
const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
227 MostDerivedLength = I + 1;
235 return MostDerivedLength;
239 struct SubobjectDesignator {
243 unsigned Invalid : 1;
246 unsigned IsOnePastTheEnd : 1;
249 unsigned FirstEntryIsAnUnsizedArray : 1;
252 unsigned MostDerivedIsArrayElement : 1;
256 unsigned MostDerivedPathLength : 28;
265 uint64_t MostDerivedArraySize;
275 SubobjectDesignator() : Invalid(
true) {}
277 explicit SubobjectDesignator(
QualType T)
278 : Invalid(
false), IsOnePastTheEnd(
false),
279 FirstEntryIsAnUnsizedArray(
false), MostDerivedIsArrayElement(
false),
280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
284 : Invalid(!
V.isLValue() || !
V.hasLValuePath()), IsOnePastTheEnd(
false),
285 FirstEntryIsAnUnsizedArray(
false), MostDerivedIsArrayElement(
false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(
V.isLValue() &&
"Non-LValue used to make an LValue designator?");
289 IsOnePastTheEnd =
V.isLValueOnePastTheEnd();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292 if (
V.getLValueBase()) {
293 bool IsArray =
false;
294 bool FirstIsUnsizedArray =
false;
295 MostDerivedPathLength = findMostDerivedSubobject(
296 Ctx,
V.getLValueBase(),
V.getLValuePath(), MostDerivedArraySize,
297 MostDerivedType, IsArray, FirstIsUnsizedArray);
298 MostDerivedIsArrayElement = IsArray;
299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
305 unsigned NewLength) {
309 assert(
Base &&
"cannot truncate path for null pointer");
310 assert(NewLength <= Entries.size() &&
"not a truncation");
312 if (NewLength == Entries.size())
314 Entries.resize(NewLength);
316 bool IsArray =
false;
317 bool FirstIsUnsizedArray =
false;
318 MostDerivedPathLength = findMostDerivedSubobject(
319 Ctx,
Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320 FirstIsUnsizedArray);
321 MostDerivedIsArrayElement = IsArray;
322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
332 bool isMostDerivedAnUnsizedArray()
const {
333 assert(!Invalid &&
"Calling this makes no sense on invalid designators");
334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339 uint64_t getMostDerivedArraySize()
const {
340 assert(!isMostDerivedAnUnsizedArray() &&
"Unsized array has no size");
341 return MostDerivedArraySize;
345 bool isOnePastTheEnd()
const {
349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
376 bool isValidSubobject()
const {
379 return !isOnePastTheEnd();
387 assert(!Invalid &&
"invalid designator has no subobject type");
388 return MostDerivedPathLength == Entries.size()
399 MostDerivedIsArrayElement =
true;
400 MostDerivedArraySize = CAT->
getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
405 void addUnsizedArrayUnchecked(
QualType ElemTy) {
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement =
true;
413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
414 MostDerivedPathLength = Entries.size();
418 void addDeclUnchecked(
const Decl *D,
bool Virtual =
false) {
422 if (
const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
424 MostDerivedIsArrayElement =
false;
425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
430 void addComplexUnchecked(
QualType EltTy,
bool Imag) {
435 MostDerivedType = EltTy;
436 MostDerivedIsArrayElement =
true;
437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
const Expr *E);
441 void diagnosePointerArithmetic(EvalInfo &Info,
const Expr *E,
444 void adjustIndex(EvalInfo &Info,
const Expr *E,
APSInt N) {
445 if (Invalid || !N)
return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
453 Entries.back().getAsArrayIndex() + TruncatedN);
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471 (llvm::APInt&)N += ArrayIndex;
472 assert(N.ugt(ArraySize) &&
"bounds check failed for in-bounds index");
473 diagnosePointerArithmetic(Info, E, N);
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&
480 "bounds check succeeded for out-of-bounds index");
485 IsOnePastTheEnd = (ArrayIndex != 0);
490 enum class ScopeKind {
498 CallRef() : OrigCallee(), CallIndex(0), Version() {}
499 CallRef(
const FunctionDecl *Callee,
unsigned CallIndex,
unsigned Version)
500 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
502 explicit operator bool()
const {
return OrigCallee; }
528 CallStackFrame *Caller;
550 typedef std::pair<const void *, unsigned> MapKeyTy;
551 typedef std::map<MapKeyTy, APValue>
MapTy;
563 unsigned CurTempVersion = TempVersionStack.back();
565 unsigned getTempVersion()
const {
return TempVersionStack.back(); }
567 void pushTempVersion() {
568 TempVersionStack.push_back(++CurTempVersion);
571 void popTempVersion() {
572 TempVersionStack.pop_back();
576 return {Callee, Index, ++CurTempVersion};
587 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
588 FieldDecl *LambdaThisCaptureField =
nullptr;
590 CallStackFrame(EvalInfo &Info,
SourceRange CallRange,
596 APValue *getTemporary(
const void *Key,
unsigned Version) {
597 MapKeyTy KV(Key, Version);
598 auto LB = Temporaries.lower_bound(KV);
599 if (LB != Temporaries.end() && LB->first == KV)
605 APValue *getCurrentTemporary(
const void *Key) {
606 auto UB = Temporaries.upper_bound(MapKeyTy(Key,
UINT_MAX));
607 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
608 return &std::prev(UB)->second;
613 unsigned getCurrentTemporaryVersion(
const void *Key)
const {
614 auto UB = Temporaries.upper_bound(MapKeyTy(Key,
UINT_MAX));
615 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
616 return std::prev(UB)->first.second;
624 template<
typename KeyT>
626 ScopeKind
Scope, LValue &LV);
631 void describe(llvm::raw_ostream &OS)
const override;
633 Frame *getCaller()
const override {
return Caller; }
634 SourceRange getCallRange()
const override {
return CallRange; }
635 const FunctionDecl *getCallee()
const override {
return Callee; }
637 bool isStdFunction()
const {
638 for (
const DeclContext *DC = Callee; DC; DC = DC->getParent())
639 if (DC->isStdNamespace())
650 class ThisOverrideRAII {
652 ThisOverrideRAII(CallStackFrame &Frame,
const LValue *NewThis,
bool Enable)
653 : Frame(Frame), OldThis(Frame.This) {
655 Frame.This = NewThis;
657 ~ThisOverrideRAII() {
658 Frame.This = OldThis;
661 CallStackFrame &Frame;
662 const LValue *OldThis;
667 class ExprTimeTraceScope {
669 ExprTimeTraceScope(
const Expr *E,
const ASTContext &Ctx, StringRef Name)
670 : TimeScope(Name, [E, &Ctx] {
675 llvm::TimeTraceScope TimeScope;
680 const LValue &This,
QualType ThisType);
688 llvm::PointerIntPair<APValue*, 2, ScopeKind>
Value;
699 bool isDestroyedAtEndOf(ScopeKind K)
const {
700 return (
int)
Value.getInt() >= (
int)K;
702 bool endLifetime(EvalInfo &Info,
bool RunDestructors) {
703 if (RunDestructors) {
706 Loc = VD->getLocation();
708 Loc = E->getExprLoc();
715 bool hasSideEffect() {
721 struct ObjectUnderConstruction {
724 friend bool operator==(
const ObjectUnderConstruction &LHS,
725 const ObjectUnderConstruction &RHS) {
726 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
728 friend llvm::hash_code
hash_value(
const ObjectUnderConstruction &Obj) {
729 return llvm::hash_combine(Obj.Base, Obj.Path);
732 enum class ConstructionPhase {
743template<>
struct DenseMapInfo<ObjectUnderConstruction> {
744 using Base = DenseMapInfo<APValue::LValueBase>;
746 return {Base::getEmptyKey(), {}}; }
748 return {Base::getTombstoneKey(), {}};
753 static bool isEqual(
const ObjectUnderConstruction &LHS,
754 const ObjectUnderConstruction &RHS) {
768 const Expr *AllocExpr =
nullptr;
779 if (
auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
780 return NE->isArray() ? ArrayNew : New;
781 assert(isa<CallExpr>(AllocExpr));
786 struct DynAllocOrder {
814 CallStackFrame *CurrentCall;
817 unsigned CallStackDepth;
820 unsigned NextCallIndex;
829 bool EnableNewConstInterp;
833 CallStackFrame BottomFrame;
843 enum class EvaluatingDeclKind {
850 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
857 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
858 ObjectsUnderConstruction;
863 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
866 unsigned NumHeapAllocs = 0;
868 struct EvaluatingConstructorRAII {
870 ObjectUnderConstruction
Object;
872 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
876 EI.ObjectsUnderConstruction
877 .insert({
Object, HasBases ? ConstructionPhase::Bases
878 : ConstructionPhase::AfterBases})
881 void finishedConstructingBases() {
882 EI.ObjectsUnderConstruction[
Object] = ConstructionPhase::AfterBases;
884 void finishedConstructingFields() {
885 EI.ObjectsUnderConstruction[
Object] = ConstructionPhase::AfterFields;
887 ~EvaluatingConstructorRAII() {
888 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
892 struct EvaluatingDestructorRAII {
894 ObjectUnderConstruction
Object;
896 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
898 DidInsert = EI.ObjectsUnderConstruction
899 .insert({
Object, ConstructionPhase::Destroying})
902 void startedDestroyingBases() {
903 EI.ObjectsUnderConstruction[
Object] =
904 ConstructionPhase::DestroyingBases;
906 ~EvaluatingDestructorRAII() {
908 EI.ObjectsUnderConstruction.erase(Object);
915 return ObjectsUnderConstruction.lookup({
Base, Path});
920 unsigned SpeculativeEvaluationDepth = 0;
928 bool HasActiveDiagnostic;
932 bool HasFoldFailureDiagnostic;
937 bool CheckingPotentialConstantExpression =
false;
945 bool CheckingForUndefinedBehavior =
false;
947 enum EvaluationMode {
950 EM_ConstantExpression,
957 EM_ConstantExpressionUnevaluated,
965 EM_IgnoreSideEffects,
970 bool checkingPotentialConstantExpression()
const override {
971 return CheckingPotentialConstantExpression;
977 bool checkingForUndefinedBehavior()
const override {
978 return CheckingForUndefinedBehavior;
982 : Ctx(const_cast<
ASTContext &>(
C)), EvalStatus(S), CurrentCall(nullptr),
983 CallStackDepth(0), NextCallIndex(1),
984 StepsLeft(
C.getLangOpts().ConstexprStepLimit),
985 EnableNewConstInterp(
C.getLangOpts().EnableNewConstInterp),
989 EvaluatingDecl((const
ValueDecl *)nullptr),
990 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(
false),
991 HasFoldFailureDiagnostic(
false), EvalMode(Mode) {}
997 ASTContext &getCtx()
const override {
return Ctx; }
1000 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1001 EvaluatingDecl =
Base;
1002 IsEvaluatingDecl = EDK;
1003 EvaluatingDeclValue = &
Value;
1009 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1011 if (NextCallIndex == 0) {
1013 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1016 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1018 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1019 << getLangOpts().ConstexprCallDepth;
1024 uint64_t ElemCount,
bool Diag) {
1030 ElemCount >
uint64_t(std::numeric_limits<unsigned>::max())) {
1032 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1042 if (ElemCount > Limit) {
1044 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1045 << ElemCount << Limit;
1051 std::pair<CallStackFrame *, unsigned>
1052 getCallFrameAndDepth(
unsigned CallIndex) {
1053 assert(CallIndex &&
"no call index in getCallFrameAndDepth");
1056 unsigned Depth = CallStackDepth;
1057 CallStackFrame *Frame = CurrentCall;
1058 while (Frame->Index > CallIndex) {
1059 Frame = Frame->Caller;
1062 if (Frame->Index == CallIndex)
1063 return {Frame, Depth};
1064 return {
nullptr, 0};
1067 bool nextStep(
const Stmt *S) {
1069 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1079 std::optional<DynAlloc *> Result;
1080 auto It = HeapAllocs.find(DA);
1081 if (It != HeapAllocs.end())
1082 Result = &It->second;
1088 CallStackFrame *Frame = getCallFrameAndDepth(
Call.CallIndex).first;
1089 return Frame ? Frame->getTemporary(
Call.getOrigParam(PVD),
Call.Version)
1094 struct StdAllocatorCaller {
1095 unsigned FrameIndex;
1097 explicit operator bool()
const {
return FrameIndex != 0; };
1100 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName)
const {
1101 for (
const CallStackFrame *
Call = CurrentCall;
Call != &BottomFrame;
1103 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(
Call->Callee);
1107 if (!FnII || !FnII->
isStr(FnName))
1111 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1117 if (CTSD->isInStdNamespace() && ClassII &&
1118 ClassII->
isStr(
"allocator") && TAL.
size() >= 1 &&
1120 return {
Call->Index, TAL[0].getAsType()};
1126 void performLifetimeExtension() {
1128 llvm::erase_if(CleanupStack, [](Cleanup &
C) {
1129 return !
C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1136 bool discardCleanups() {
1137 for (Cleanup &
C : CleanupStack) {
1138 if (
C.hasSideEffect() && !noteSideEffect()) {
1139 CleanupStack.clear();
1143 CleanupStack.clear();
1148 interp::Frame *getCurrentFrame()
override {
return CurrentCall; }
1149 const interp::Frame *getBottomFrame()
const override {
return &BottomFrame; }
1151 bool hasActiveDiagnostic()
override {
return HasActiveDiagnostic; }
1152 void setActiveDiagnostic(
bool Flag)
override { HasActiveDiagnostic = Flag; }
1154 void setFoldFailureDiagnostic(
bool Flag)
override {
1155 HasFoldFailureDiagnostic = Flag;
1166 bool hasPriorDiagnostic()
override {
1167 if (!EvalStatus.
Diag->empty()) {
1169 case EM_ConstantFold:
1170 case EM_IgnoreSideEffects:
1171 if (!HasFoldFailureDiagnostic)
1175 case EM_ConstantExpression:
1176 case EM_ConstantExpressionUnevaluated:
1177 setActiveDiagnostic(
false);
1184 unsigned getCallStackDepth()
override {
return CallStackDepth; }
1189 bool keepEvaluatingAfterSideEffect() {
1191 case EM_IgnoreSideEffects:
1194 case EM_ConstantExpression:
1195 case EM_ConstantExpressionUnevaluated:
1196 case EM_ConstantFold:
1199 return checkingPotentialConstantExpression() ||
1200 checkingForUndefinedBehavior();
1202 llvm_unreachable(
"Missed EvalMode case");
1207 bool noteSideEffect() {
1209 return keepEvaluatingAfterSideEffect();
1213 bool keepEvaluatingAfterUndefinedBehavior() {
1215 case EM_IgnoreSideEffects:
1216 case EM_ConstantFold:
1219 case EM_ConstantExpression:
1220 case EM_ConstantExpressionUnevaluated:
1221 return checkingForUndefinedBehavior();
1223 llvm_unreachable(
"Missed EvalMode case");
1229 bool noteUndefinedBehavior()
override {
1231 return keepEvaluatingAfterUndefinedBehavior();
1236 bool keepEvaluatingAfterFailure()
const override {
1241 case EM_ConstantExpression:
1242 case EM_ConstantExpressionUnevaluated:
1243 case EM_ConstantFold:
1244 case EM_IgnoreSideEffects:
1245 return checkingPotentialConstantExpression() ||
1246 checkingForUndefinedBehavior();
1248 llvm_unreachable(
"Missed EvalMode case");
1261 [[nodiscard]]
bool noteFailure() {
1269 bool KeepGoing = keepEvaluatingAfterFailure();
1274 class ArrayInitLoopIndex {
1279 ArrayInitLoopIndex(EvalInfo &Info)
1280 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1281 Info.ArrayInitIndex = 0;
1283 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1285 operator uint64_t&() {
return Info.ArrayInitIndex; }
1290 struct FoldConstant {
1293 bool HadNoPriorDiags;
1294 EvalInfo::EvaluationMode OldMode;
1296 explicit FoldConstant(EvalInfo &Info,
bool Enabled)
1299 HadNoPriorDiags(Info.EvalStatus.
Diag &&
1300 Info.EvalStatus.
Diag->empty() &&
1301 !Info.EvalStatus.HasSideEffects),
1302 OldMode(Info.EvalMode) {
1304 Info.EvalMode = EvalInfo::EM_ConstantFold;
1306 void keepDiagnostics() { Enabled =
false; }
1308 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1309 !Info.EvalStatus.HasSideEffects)
1310 Info.EvalStatus.Diag->clear();
1311 Info.EvalMode = OldMode;
1317 struct IgnoreSideEffectsRAII {
1319 EvalInfo::EvaluationMode OldMode;
1320 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1321 : Info(Info), OldMode(Info.EvalMode) {
1322 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1325 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1330 class SpeculativeEvaluationRAII {
1331 EvalInfo *Info =
nullptr;
1333 unsigned OldSpeculativeEvaluationDepth = 0;
1335 void moveFromAndCancel(SpeculativeEvaluationRAII &&
Other) {
1337 OldStatus =
Other.OldStatus;
1338 OldSpeculativeEvaluationDepth =
Other.OldSpeculativeEvaluationDepth;
1339 Other.Info =
nullptr;
1342 void maybeRestoreState() {
1346 Info->EvalStatus = OldStatus;
1347 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1351 SpeculativeEvaluationRAII() =
default;
1353 SpeculativeEvaluationRAII(
1355 : Info(&Info), OldStatus(Info.EvalStatus),
1356 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1357 Info.EvalStatus.Diag = NewDiag;
1358 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1361 SpeculativeEvaluationRAII(
const SpeculativeEvaluationRAII &
Other) =
delete;
1362 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&
Other) {
1363 moveFromAndCancel(std::move(
Other));
1366 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&
Other) {
1367 maybeRestoreState();
1368 moveFromAndCancel(std::move(
Other));
1372 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1377 template<ScopeKind Kind>
1380 unsigned OldStackSize;
1382 ScopeRAII(EvalInfo &Info)
1383 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1386 Info.CurrentCall->pushTempVersion();
1388 bool destroy(
bool RunDestructors =
true) {
1389 bool OK =
cleanup(Info, RunDestructors, OldStackSize);
1394 if (OldStackSize != -1U)
1398 Info.CurrentCall->popTempVersion();
1401 static bool cleanup(EvalInfo &Info,
bool RunDestructors,
1402 unsigned OldStackSize) {
1403 assert(OldStackSize <= Info.CleanupStack.size() &&
1404 "running cleanups out of order?");
1409 for (
unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1410 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1411 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1419 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1420 if (Kind != ScopeKind::Block)
1422 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &
C) {
1423 return C.isDestroyedAtEndOf(Kind);
1425 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1429 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1430 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1431 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1434bool SubobjectDesignator::checkSubobject(EvalInfo &Info,
const Expr *E,
1438 if (isOnePastTheEnd()) {
1439 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1450void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1452 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1457void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1462 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1463 Info.CCEDiag(E, diag::note_constexpr_array_index)
1465 <<
static_cast<unsigned>(getMostDerivedArraySize());
1467 Info.CCEDiag(E, diag::note_constexpr_array_index)
1472CallStackFrame::CallStackFrame(EvalInfo &Info,
SourceRange CallRange,
1477 Index(Info.NextCallIndex++) {
1478 Info.CurrentCall =
this;
1479 ++Info.CallStackDepth;
1482CallStackFrame::~CallStackFrame() {
1483 assert(Info.CurrentCall ==
this &&
"calls retired out of order");
1484 --Info.CallStackDepth;
1485 Info.CurrentCall = Caller;
1507 llvm_unreachable(
"unknown access kind");
1541 llvm_unreachable(
"unknown access kind");
1545 struct ComplexValue {
1553 ComplexValue() : FloatReal(
APFloat::Bogus()), FloatImag(
APFloat::Bogus()) {}
1555 void makeComplexFloat() { IsInt =
false; }
1556 bool isComplexFloat()
const {
return !IsInt; }
1557 APFloat &getComplexFloatReal() {
return FloatReal; }
1558 APFloat &getComplexFloatImag() {
return FloatImag; }
1560 void makeComplexInt() { IsInt =
true; }
1561 bool isComplexInt()
const {
return IsInt; }
1562 APSInt &getComplexIntReal() {
return IntReal; }
1563 APSInt &getComplexIntImag() {
return IntImag; }
1566 if (isComplexFloat())
1572 assert(
v.isComplexFloat() ||
v.isComplexInt());
1573 if (
v.isComplexFloat()) {
1575 FloatReal =
v.getComplexFloatReal();
1576 FloatImag =
v.getComplexFloatImag();
1579 IntReal =
v.getComplexIntReal();
1580 IntImag =
v.getComplexIntImag();
1590 bool InvalidBase : 1;
1593 CharUnits &getLValueOffset() {
return Offset; }
1594 const CharUnits &getLValueOffset()
const {
return Offset; }
1595 SubobjectDesignator &getLValueDesignator() {
return Designator; }
1596 const SubobjectDesignator &getLValueDesignator()
const {
return Designator;}
1597 bool isNullPointer()
const {
return IsNullPtr;}
1599 unsigned getLValueCallIndex()
const {
return Base.getCallIndex(); }
1600 unsigned getLValueVersion()
const {
return Base.getVersion(); }
1606 assert(!InvalidBase &&
"APValues can't handle invalid LValue bases");
1612 assert(
V.isLValue() &&
"Setting LValue from a non-LValue?");
1613 Base =
V.getLValueBase();
1614 Offset =
V.getLValueOffset();
1615 InvalidBase =
false;
1617 IsNullPtr =
V.isNullPointer();
1624 const auto *E = B.
get<
const Expr *>();
1625 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1626 "Unexpected type of invalid base");
1632 InvalidBase = BInvalid;
1633 Designator = SubobjectDesignator(getType(B));
1641 InvalidBase =
false;
1652 moveInto(Printable);
1659 template <
typename GenDiagType>
1660 bool checkNullPointerDiagnosingWith(
const GenDiagType &GenDiag) {
1672 bool checkNullPointer(EvalInfo &Info,
const Expr *E,
1674 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1675 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1679 bool checkNullPointerForFoldAccess(EvalInfo &Info,
const Expr *E,
1681 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1682 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1693 void addDecl(EvalInfo &Info,
const Expr *E,
1698 void addUnsizedArray(EvalInfo &Info,
const Expr *E,
QualType ElemTy) {
1700 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1705 assert(getType(
Base)->isPointerType() || getType(
Base)->isArrayType());
1706 Designator.FirstEntryIsAnUnsizedArray =
true;
1714 void addComplex(EvalInfo &Info,
const Expr *E,
QualType EltTy,
bool Imag) {
1718 void clearIsNullPointer() {
1721 void adjustOffsetAndIndex(EvalInfo &Info,
const Expr *E,
1731 uint64_t Offset64 = Offset.getQuantity();
1733 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1738 clearIsNullPointer();
1743 clearIsNullPointer();
1750 : DeclAndIsDerivedMember(
Decl,
false) {}
1755 return DeclAndIsDerivedMember.getPointer();
1758 bool isDerivedMember()
const {
1759 return DeclAndIsDerivedMember.getInt();
1763 return cast<CXXRecordDecl>(
1764 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1768 V =
APValue(getDecl(), isDerivedMember(), Path);
1771 assert(
V.isMemberPointer());
1772 DeclAndIsDerivedMember.setPointer(
V.getMemberPointerDecl());
1773 DeclAndIsDerivedMember.setInt(
V.isMemberPointerToDerivedMember());
1776 Path.insert(Path.end(),
P.begin(),
P.end());
1782 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1790 assert(!Path.empty());
1792 if (Path.size() >= 2)
1796 if (
Expected->getCanonicalDecl() !=
Class->getCanonicalDecl()) {
1812 if (!isDerivedMember()) {
1813 Path.push_back(Derived);
1816 if (!castBack(Derived))
1819 DeclAndIsDerivedMember.setInt(
false);
1827 DeclAndIsDerivedMember.setInt(
true);
1828 if (isDerivedMember()) {
1829 Path.push_back(
Base);
1832 return castBack(
Base);
1837 static bool operator==(
const MemberPtr &LHS,
const MemberPtr &RHS) {
1838 if (!LHS.getDecl() || !RHS.getDecl())
1839 return !LHS.getDecl() && !RHS.getDecl();
1840 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1842 return LHS.Path == RHS.Path;
1848 const LValue &This,
const Expr *E,
1849 bool AllowNonLiteralTypes =
false);
1851 bool InvalidBaseOK =
false);
1853 bool InvalidBaseOK =
false);
1883 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1884 Int = Int.extend(Int.getBitWidth() + 1);
1885 Int.setIsSigned(
true);
1890template<
typename KeyT>
1892 ScopeKind
Scope, LValue &LV) {
1893 unsigned Version = getTempVersion();
1896 return createLocal(
Base, Key, T,
Scope);
1902 assert(Args.CallIndex == Index &&
"creating parameter in wrong frame");
1908 return createLocal(
Base, PVD, PVD->
getType(), ScopeKind::Call);
1913 assert(
Base.getCallIndex() == Index &&
"lvalue for wrong frame");
1914 unsigned Version =
Base.getVersion();
1915 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1916 assert(Result.isAbsent() &&
"local created multiple times");
1922 if (Index <= Info.SpeculativeEvaluationDepth) {
1924 Info.noteSideEffect();
1926 Info.CleanupStack.push_back(Cleanup(&Result,
Base, T,
Scope));
1933 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1939 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1940 std::forward_as_tuple(DA), std::tuple<>());
1941 assert(Result.second &&
"reused a heap alloc index?");
1942 Result.first->second.AllocExpr = E;
1943 return &Result.first->second.Value;
1947void CallStackFrame::describe(raw_ostream &Out)
const {
1948 unsigned ArgIndex = 0;
1950 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1951 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1954 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1957 if (This && IsMemberCall) {
1958 if (
const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(
CallExpr)) {
1959 const Expr *
Object = MCE->getImplicitObjectArgument();
1960 Object->printPretty(Out,
nullptr, Info.Ctx.getPrintingPolicy(),
1962 if (
Object->getType()->isPointerType())
1966 }
else if (
const auto *OCE =
1967 dyn_cast_if_present<CXXOperatorCallExpr>(
CallExpr)) {
1968 OCE->getArg(0)->printPretty(Out,
nullptr,
1969 Info.Ctx.getPrintingPolicy(),
1974 This->moveInto(Val);
1977 Info.Ctx.getLValueReferenceType(
This->Designator.MostDerivedType));
1980 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1982 IsMemberCall =
false;
1988 E =
Callee->param_end(); I != E; ++I, ++ArgIndex) {
1989 if (ArgIndex > (
unsigned)IsMemberCall)
1993 APValue *
V = Info.getParamSlot(Arguments, Param);
1995 V->printPretty(Out, Info.Ctx, Param->
getType());
1999 if (ArgIndex == 0 && IsMemberCall)
2000 Out <<
"->" << *
Callee <<
'(';
2014 return Info.noteSideEffect();
2021 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2022 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2023 Builtin == Builtin::BI__builtin_function_start);
2037 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
2038 return VD->hasGlobalStorage();
2039 if (isa<TemplateParamObjectDecl>(D))
2044 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2054 case Expr::CompoundLiteralExprClass: {
2058 case Expr::MaterializeTemporaryExprClass:
2061 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() ==
SD_Static;
2063 case Expr::StringLiteralClass:
2064 case Expr::PredefinedExprClass:
2065 case Expr::ObjCStringLiteralClass:
2066 case Expr::ObjCEncodeExprClass:
2068 case Expr::ObjCBoxedExprClass:
2069 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2070 case Expr::CallExprClass:
2073 case Expr::AddrLabelExprClass:
2077 case Expr::BlockExprClass:
2078 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2081 case Expr::SourceLocExprClass:
2083 case Expr::ImplicitValueInitExprClass:
2095 return LVal.Base.dyn_cast<
const ValueDecl*>();
2099 if (
Value.getLValueCallIndex())
2102 return E && !isa<MaterializeTemporaryExpr>(E);
2122 if (!A.getLValueBase())
2123 return !B.getLValueBase();
2124 if (!B.getLValueBase())
2127 if (A.getLValueBase().getOpaqueValue() !=
2128 B.getLValueBase().getOpaqueValue())
2131 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2132 A.getLValueVersion() == B.getLValueVersion();
2136 assert(
Base &&
"no location for a null lvalue");
2142 if (
auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2144 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2145 if (F->Arguments.CallIndex ==
Base.getCallIndex() &&
2146 F->Arguments.Version ==
Base.getVersion() && F->Callee &&
2147 Idx < F->Callee->getNumParams()) {
2148 VD = F->Callee->getParamDecl(Idx);
2155 Info.Note(VD->
getLocation(), diag::note_declared_at);
2157 Info.Note(E->
getExprLoc(), diag::note_constexpr_temporary_here);
2160 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2161 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2162 diag::note_constexpr_dynamic_alloc_here);
2195 const SubobjectDesignator &
Designator = LVal.getLValueDesignator();
2203 if (isTemplateArgument(Kind)) {
2204 int InvalidBaseKind = -1;
2207 InvalidBaseKind = 0;
2208 else if (isa_and_nonnull<StringLiteral>(BaseE))
2209 InvalidBaseKind = 1;
2210 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2211 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2212 InvalidBaseKind = 2;
2213 else if (
auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2214 InvalidBaseKind = 3;
2215 Ident = PE->getIdentKindName();
2218 if (InvalidBaseKind != -1) {
2219 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2220 << IsReferenceType << !
Designator.Entries.empty() << InvalidBaseKind
2226 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2227 FD && FD->isImmediateFunction()) {
2228 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2230 Info.Note(FD->getLocation(), diag::note_declared_at);
2238 if (Info.getLangOpts().CPlusPlus11) {
2239 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2240 << IsReferenceType << !
Designator.Entries.empty() << !!BaseVD
2242 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2243 if (VarD && VarD->isConstexpr()) {
2249 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2261 assert((Info.checkingPotentialConstantExpression() ||
2262 LVal.getLValueCallIndex() == 0) &&
2263 "have call index for global lvalue");
2266 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2267 << IsReferenceType << !
Designator.Entries.empty();
2273 if (
const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2275 if (Var->getTLSKind())
2281 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2287 if (Info.getCtx().getLangOpts().CUDA &&
2288 Info.getCtx().getLangOpts().CUDAIsDevice &&
2289 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2290 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2291 !Var->hasAttr<CUDAConstantAttr>() &&
2292 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2293 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2294 Var->hasAttr<HIPManagedAttr>())
2298 if (
const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2309 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2310 FD->hasAttr<DLLImportAttr>())
2314 }
else if (
const auto *MTE =
2315 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2316 if (CheckedTemps.insert(MTE).second) {
2319 Info.FFDiag(MTE->getExprLoc(),
2320 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2325 APValue *
V = MTE->getOrCreateValue(
false);
2326 assert(
V &&
"evasluation result refers to uninitialised temporary");
2328 Info, MTE->getExprLoc(), TempType, *
V, Kind,
2329 nullptr, CheckedTemps))
2336 if (!IsReferenceType)
2348 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2349 << !
Designator.Entries.empty() << !!BaseVD << BaseVD;
2364 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(
Member);
2367 if (FD->isImmediateFunction()) {
2368 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << 0;
2369 Info.Note(FD->getLocation(), diag::note_declared_at);
2372 return isForManglingOnly(Kind) || FD->isVirtual() ||
2373 !FD->hasAttr<DLLImportAttr>();
2379 const LValue *This =
nullptr) {
2396 if (This && Info.EvaluatingDecl == This->getLValueBase())
2400 if (Info.getLangOpts().CPlusPlus11)
2401 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2404 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2415 if (SubobjectDecl) {
2416 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2417 << 1 << SubobjectDecl;
2419 diag::note_constexpr_subobject_declared_here);
2421 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2430 Type = AT->getValueType();
2435 if (
Value.isArray()) {
2437 for (
unsigned I = 0, N =
Value.getArrayInitializedElts(); I != N; ++I) {
2439 Value.getArrayInitializedElt(I), Kind,
2440 SubobjectDecl, CheckedTemps))
2443 if (!
Value.hasArrayFiller())
2446 Value.getArrayFiller(), Kind, SubobjectDecl,
2449 if (
Value.isUnion() &&
Value.getUnionField()) {
2452 Value.getUnionValue(), Kind,
Value.getUnionField(), CheckedTemps);
2454 if (
Value.isStruct()) {
2456 if (
const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2457 unsigned BaseIndex = 0;
2459 const APValue &BaseValue =
Value.getStructBase(BaseIndex);
2462 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2463 << BS.getType() <<
SourceRange(TypeBeginLoc, BS.getEndLoc());
2473 for (
const auto *I : RD->
fields()) {
2474 if (I->isUnnamedBitfield())
2478 Value.getStructField(I->getFieldIndex()), Kind,
2484 if (
Value.isLValue() &&
2485 CERK == CheckEvaluationResultKind::ConstantExpression) {
2487 LVal.setFrom(Info.Ctx,
Value);
2492 if (
Value.isMemberPointer() &&
2493 CERK == CheckEvaluationResultKind::ConstantExpression)
2513 nullptr, CheckedTemps);
2522 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc,
Type,
Value,
2523 ConstantExprKind::Normal,
nullptr, CheckedTemps);
2529 if (!Info.HeapAllocs.empty()) {
2533 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2534 diag::note_constexpr_memory_leak)
2535 <<
unsigned(Info.HeapAllocs.size() - 1);
2543 if (!
Value.getLValueBase()) {
2545 Result = !
Value.getLValueOffset().isZero();
2563 Result = Val.
getInt().getBoolValue();
2595 llvm_unreachable(
"unknown APValue kind");
2601 assert(E->
isPRValue() &&
"missing lvalue-to-rvalue conv in bool condition");
2610 const T &SrcValue,
QualType DestType) {
2611 Info.CCEDiag(E, diag::note_constexpr_overflow)
2612 << SrcValue << DestType;
2613 return Info.noteUndefinedBehavior();
2619 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2623 Result =
APSInt(DestWidth, !DestSigned);
2625 if (
Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2626 & APFloat::opInvalidOp)
2637 llvm::RoundingMode RM =
2639 if (RM == llvm::RoundingMode::Dynamic)
2640 RM = llvm::RoundingMode::NearestTiesToEven;
2646 APFloat::opStatus St) {
2649 if (Info.InConstantContext)
2653 if ((St & APFloat::opInexact) &&
2657 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2661 if ((St != APFloat::opOK) &&
2664 FPO.getAllowFEnvAccess())) {
2665 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2669 if ((St & APFloat::opStatus::opInvalidOp) &&
2688 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2690 APFloat::opStatus St;
2691 APFloat
Value = Result;
2693 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2700 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2706 Result =
Value.getBoolValue();
2713 QualType DestType, APFloat &Result) {
2714 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2716 APFloat::opStatus St = Result.convertFromAPInt(
Value,
Value.isSigned(), RM);
2722 assert(FD->
isBitField() &&
"truncateBitfieldValue on non-bitfield");
2724 if (!
Value.isInt()) {
2728 assert(
Value.isLValue() &&
"integral value neither int nor lvalue?");
2734 unsigned OldBitWidth = Int.getBitWidth();
2736 if (NewBitWidth < OldBitWidth)
2737 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2744template<
typename Operation>
2747 unsigned BitWidth, Operation Op,
2749 if (LHS.isUnsigned()) {
2750 Result = Op(LHS, RHS);
2754 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)),
false);
2755 Result =
Value.trunc(LHS.getBitWidth());
2756 if (Result.extend(BitWidth) !=
Value) {
2757 if (Info.checkingForUndefinedBehavior())
2758 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
2759 diag::warn_integer_constant_overflow)
2770 bool HandleOverflowResult =
true;
2777 std::multiplies<APSInt>(), Result);
2780 std::plus<APSInt>(), Result);
2783 std::minus<APSInt>(), Result);
2784 case BO_And: Result = LHS & RHS;
return true;
2785 case BO_Xor: Result = LHS ^ RHS;
return true;
2786 case BO_Or: Result = LHS | RHS;
return true;
2790 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2796 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2797 LHS.isMinSignedValue())
2799 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->
getType());
2800 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2801 return HandleOverflowResult;
2803 if (Info.getLangOpts().OpenCL)
2805 RHS &=
APSInt(llvm::APInt(RHS.getBitWidth(),
2806 static_cast<uint64_t
>(LHS.getBitWidth() - 1)),
2808 else if (RHS.isSigned() && RHS.isNegative()) {
2811 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2818 unsigned SA = (
unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2820 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2821 << RHS << E->
getType() << LHS.getBitWidth();
2822 }
else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2827 if (LHS.isNegative())
2828 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2829 else if (LHS.countl_zero() < SA)
2830 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2836 if (Info.getLangOpts().OpenCL)
2838 RHS &=
APSInt(llvm::APInt(RHS.getBitWidth(),
2839 static_cast<uint64_t
>(LHS.getBitWidth() - 1)),
2841 else if (RHS.isSigned() && RHS.isNegative()) {
2844 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2851 unsigned SA = (
unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2853 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2854 << RHS << E->
getType() << LHS.getBitWidth();
2859 case BO_LT: Result = LHS < RHS;
return true;
2860 case BO_GT: Result = LHS > RHS;
return true;
2861 case BO_LE: Result = LHS <= RHS;
return true;
2862 case BO_GE: Result = LHS >= RHS;
return true;
2863 case BO_EQ: Result = LHS == RHS;
return true;
2864 case BO_NE: Result = LHS != RHS;
return true;
2866 llvm_unreachable(
"BO_Cmp should be handled elsewhere");
2873 const APFloat &RHS) {
2875 APFloat::opStatus St;
2881 St = LHS.multiply(RHS, RM);
2884 St = LHS.add(RHS, RM);
2887 St = LHS.subtract(RHS, RM);
2893 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2894 St = LHS.divide(RHS, RM);
2903 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2904 return Info.noteUndefinedBehavior();
2912 const APInt &RHSValue, APInt &Result) {
2913 bool LHS = (LHSValue != 0);
2914 bool RHS = (RHSValue != 0);
2916 if (Opcode == BO_LAnd)
2917 Result = LHS && RHS;
2919 Result = LHS || RHS;
2924 const APFloat &RHSValue, APInt &Result) {
2925 bool LHS = !LHSValue.isZero();
2926 bool RHS = !RHSValue.isZero();
2928 if (Opcode == BO_LAnd)
2929 Result = LHS && RHS;
2931 Result = LHS || RHS;
2937 const APValue &RHSValue, APInt &Result) {
2941 RHSValue.
getInt(), Result);
2947template <
typename APTy>
2950 const APTy &RHSValue, APInt &Result) {
2953 llvm_unreachable(
"unsupported binary operator");
2955 Result = (LHSValue == RHSValue);
2958 Result = (LHSValue != RHSValue);
2961 Result = (LHSValue < RHSValue);
2964 Result = (LHSValue > RHSValue);
2967 Result = (LHSValue <= RHSValue);
2970 Result = (LHSValue >= RHSValue);
2984 const APValue &RHSValue, APInt &Result) {
2988 RHSValue.
getInt(), Result);
2999 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3000 "Operation not supported on vector types");
3004 QualType EltTy = VT->getElementType();
3011 "A vector result that isn't a vector OR uncalculated LValue");
3017 RHSValue.
getVectorLength() == NumElements &&
"Different vector sizes");
3021 for (
unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3026 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3028 bool Success =
true;
3036 RHSElt.
getInt(), EltResult);
3042 ResultElements.emplace_back(EltResult);
3047 "Mismatched LHS/RHS/Result Type");
3048 APFloat LHSFloat = LHSElt.
getFloat();
3056 ResultElements.emplace_back(LHSFloat);
3060 LHSValue =
APValue(ResultElements.data(), ResultElements.size());
3068 unsigned TruncatedElements) {
3069 SubobjectDesignator &D = Result.Designator;
3072 if (TruncatedElements == D.Entries.size())
3074 assert(TruncatedElements >= D.MostDerivedPathLength &&
3075 "not casting to a derived class");
3081 for (
unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3085 if (isVirtualBaseClass(D.Entries[I]))
3091 D.Entries.resize(TruncatedElements);
3101 RL = &Info.Ctx.getASTRecordLayout(Derived);
3104 Obj.getLValueOffset() += RL->getBaseClassOffset(
Base);
3105 Obj.addDecl(Info, E,
Base,
false);
3114 if (!
Base->isVirtual())
3117 SubobjectDesignator &D = Obj.Designator;
3122 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3128 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3130 Obj.addDecl(Info, E, BaseDecl,
true);
3138 PathI != PathE; ++PathI) {
3142 Type = (*PathI)->getType();
3154 llvm_unreachable(
"Class must be derived from the passed in base class!");
3169 RL = &Info.Ctx.getASTRecordLayout(FD->
getParent());
3173 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3174 LVal.addDecl(Info, E, FD);
3182 for (
const auto *
C : IFD->
chain())
3215 if (SOT == SizeOfType::SizeOf)
3216 Size = Info.Ctx.getTypeSizeInChars(
Type);
3218 Size = Info.Ctx.getTypeInfoDataSizeInChars(
Type).Width;
3235 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3241 int64_t Adjustment) {
3243 APSInt::get(Adjustment));
3258 LVal.Offset += SizeOfComponent;
3260 LVal.addComplex(Info, E, EltTy, Imag);
3274 const VarDecl *VD, CallStackFrame *Frame,
3275 unsigned Version,
APValue *&Result) {
3280 Result = Frame->getTemporary(VD, Version);
3284 if (!isa<ParmVarDecl>(VD)) {
3291 "missing value for local variable");
3292 if (Info.checkingPotentialConstantExpression())
3297 diag::note_unimplemented_constexpr_lambda_feature_ast)
3298 <<
"captures not currently allowed";
3305 if (Info.EvaluatingDecl ==
Base) {
3306 Result = Info.EvaluatingDeclValue;
3310 if (isa<ParmVarDecl>(VD)) {
3313 if (!Info.checkingPotentialConstantExpression() ||
3314 !Info.CurrentCall->Callee ||
3316 if (Info.getLangOpts().CPlusPlus11) {
3317 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3337 if (!Info.checkingPotentialConstantExpression()) {
3338 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3345 if (
Init->isValueDependent()) {
3352 if (!Info.checkingPotentialConstantExpression()) {
3353 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3354 ? diag::note_constexpr_ltor_non_constexpr
3355 : diag::note_constexpr_ltor_non_integral, 1)
3365 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3381 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3383 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3390 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3406 E = Derived->
bases_end(); I != E; ++I, ++Index) {
3407 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
Base)
3411 llvm_unreachable(
"base class missing from derived class's bases list");
3417 assert(!isa<SourceLocExpr>(Lit) &&
3418 "SourceLocExpr should have already been converted to a StringLiteral");
3421 if (
const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3423 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3424 assert(Index <= Str.size() &&
"Index too large");
3425 return APSInt::getUnsigned(Str.c_str()[Index]);
3428 if (
auto PE = dyn_cast<PredefinedExpr>(Lit))
3429 Lit = PE->getFunctionName();
3432 Info.Ctx.getAsConstantArrayType(S->getType());
3433 assert(CAT &&
"string literal isn't an array");
3435 assert(CharType->
isIntegerType() &&
"unexpected character type");
3438 if (Index < S->getLength())
3439 Value = S->getCodeUnit(Index);
3451 AllocType.isNull() ? S->getType() : AllocType);
3452 assert(CAT &&
"string literal isn't an array");
3454 assert(CharType->
isIntegerType() &&
"unexpected character type");
3456 unsigned Elts = CAT->
getSize().getZExtValue();
3458 std::min(S->getLength(), Elts), Elts);
3461 if (Result.hasArrayFiller())
3463 for (
unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3464 Value = S->getCodeUnit(I);
3471 unsigned Size = Array.getArraySize();
3472 assert(Index < Size);
3475 unsigned OldElts = Array.getArrayInitializedElts();
3476 unsigned NewElts = std::max(Index+1, OldElts * 2);
3477 NewElts = std::min(Size, std::max(NewElts, 8u));
3481 for (
unsigned I = 0; I != OldElts; ++I)
3483 for (
unsigned I = OldElts; I != NewElts; ++I)
3487 Array.swap(NewValue);
3508 for (
auto *Field : RD->
fields())
3509 if (!Field->isUnnamedBitfield() &&
3513 for (
auto &BaseSpec : RD->
bases())
3531 for (
auto *Field : RD->
fields()) {
3536 if (Field->isMutable() &&
3538 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3539 Info.Note(Field->getLocation(), diag::note_declared_at);
3547 for (
auto &BaseSpec : RD->
bases())
3557 bool MutableSubobject =
false) {
3562 switch (Info.IsEvaluatingDecl) {
3563 case EvalInfo::EvaluatingDeclKind::None:
3566 case EvalInfo::EvaluatingDeclKind::Ctor:
3568 if (Info.EvaluatingDecl ==
Base)
3573 if (
auto *BaseE =
Base.dyn_cast<
const Expr *>())
3574 if (
auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3575 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3578 case EvalInfo::EvaluatingDeclKind::Dtor:
3583 if (MutableSubobject ||
Base != Info.EvaluatingDecl)
3592 llvm_unreachable(
"unknown evaluating decl kind");
3597 return Info.CheckArraySize(
3606struct CompleteObject {
3614 CompleteObject() :
Value(nullptr) {}
3618 bool mayAccessMutableMembers(EvalInfo &Info,
AccessKinds AK)
const {
3629 if (!Info.getLangOpts().CPlusPlus14)
3634 explicit operator bool()
const {
return !
Type.isNull(); }
3639 bool IsMutable =
false) {
3653template<
typename Sub
objectHandler>
3654typename SubobjectHandler::result_type
3656 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3659 return handler.failed();
3660 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3661 if (Info.getLangOpts().CPlusPlus11)
3662 Info.FFDiag(E, Sub.isOnePastTheEnd()
3663 ? diag::note_constexpr_access_past_end
3664 : diag::note_constexpr_access_unsized_array)
3665 << handler.AccessKind;
3668 return handler.failed();
3674 const FieldDecl *VolatileField =
nullptr;
3677 for (
unsigned I = 0, N = Sub.Entries.size(); ; ++I) {
3682 if (!Info.checkingPotentialConstantExpression())
3683 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3686 return handler.failed();
3694 Info.isEvaluatingCtorDtor(
3697 ConstructionPhase::None) {
3707 if (Info.getLangOpts().CPlusPlus) {
3711 if (VolatileField) {
3714 Decl = VolatileField;
3715 }
else if (
auto *VD = Obj.Base.dyn_cast<
const ValueDecl*>()) {
3717 Loc = VD->getLocation();
3721 if (
auto *E = Obj.Base.dyn_cast<
const Expr *>())
3724 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3725 << handler.AccessKind << DiagKind <<
Decl;
3726 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3728 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3730 return handler.failed();
3738 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3740 return handler.failed();
3744 if (!handler.found(*O, ObjType))
3756 LastField =
nullptr;
3760 assert(CAT &&
"vla in literal type?");
3761 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3762 if (CAT->
getSize().ule(Index)) {
3765 if (Info.getLangOpts().CPlusPlus11)
3766 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3767 << handler.AccessKind;
3770 return handler.failed();
3777 else if (!
isRead(handler.AccessKind)) {
3779 return handler.failed();
3787 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3789 if (Info.getLangOpts().CPlusPlus11)
3790 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3791 << handler.AccessKind;
3794 return handler.failed();
3800 assert(I == N - 1 &&
"extracting subobject of scalar?");
3809 }
else if (
const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3810 if (Field->isMutable() &&
3811 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3812 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3813 << handler.AccessKind << Field;
3814 Info.Note(Field->getLocation(), diag::note_declared_at);
3815 return handler.failed();
3824 if (I == N - 1 && handler.AccessKind ==
AK_Construct) {
3832 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3833 << handler.AccessKind << Field << !UnionField << UnionField;
3834 return handler.failed();
3843 if (Field->getType().isVolatileQualified())
3844 VolatileField = Field;
3857struct ExtractSubobjectHandler {
3863 typedef bool result_type;
3864 bool failed() {
return false; }
3884 const CompleteObject &Obj,
3885 const SubobjectDesignator &Sub,
APValue &Result,
3888 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3893struct ModifySubobjectHandler {
3898 typedef bool result_type;
3904 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3910 bool failed() {
return false; }
3912 if (!checkConst(SubobjType))
3915 Subobj.
swap(NewVal);
3919 if (!checkConst(SubobjType))
3921 if (!NewVal.
isInt()) {
3930 if (!checkConst(SubobjType))
3938const AccessKinds ModifySubobjectHandler::AccessKind;
3942 const CompleteObject &Obj,
3943 const SubobjectDesignator &Sub,
3945 ModifySubobjectHandler Handler = { Info, NewVal, E };
3952 const SubobjectDesignator &A,
3953 const SubobjectDesignator &B,
3954 bool &WasArrayIndex) {
3955 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3956 for (; I != N; ++I) {
3960 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3961 WasArrayIndex =
true;
3969 if (A.Entries[I].getAsBaseOrMember() !=
3970 B.Entries[I].getAsBaseOrMember()) {
3971 WasArrayIndex =
false;
3974 if (
const FieldDecl *FD = getAsField(A.Entries[I]))
3976 ObjType = FD->getType();
3982 WasArrayIndex =
false;
3989 const SubobjectDesignator &A,
3990 const SubobjectDesignator &B) {
3991 if (A.Entries.size() != B.Entries.size())
3994 bool IsArray = A.MostDerivedIsArrayElement;
3995 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4004 return CommonLength >= A.Entries.size() - IsArray;
4011 if (LVal.InvalidBase) {
4013 return CompleteObject();
4017 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4018 return CompleteObject();
4021 CallStackFrame *Frame =
nullptr;
4023 if (LVal.getLValueCallIndex()) {
4024 std::tie(Frame, Depth) =
4025 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4027 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4028 << AK << LVal.Base.is<
const ValueDecl*>();
4030 return CompleteObject();
4041 if (Info.getLangOpts().CPlusPlus)
4042 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4046 return CompleteObject();
4051 QualType BaseType = getType(LVal.Base);
4053 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4057 BaseVal = Info.EvaluatingDeclValue;
4060 if (
auto *GD = dyn_cast<MSGuidDecl>(D)) {
4063 Info.FFDiag(E, diag::note_constexpr_modify_global);
4064 return CompleteObject();
4068 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4070 return CompleteObject();
4072 return CompleteObject(LVal.Base, &
V, GD->getType());
4076 if (
auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4078 Info.FFDiag(E, diag::note_constexpr_modify_global);
4079 return CompleteObject();
4081 return CompleteObject(LVal.Base,
const_cast<APValue *
>(&GCD->getValue()),
4086 if (
auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4088 Info.FFDiag(E, diag::note_constexpr_modify_global);
4089 return CompleteObject();
4091 return CompleteObject(LVal.Base,
const_cast<APValue *
>(&TPO->getValue()),
4102 const VarDecl *VD = dyn_cast<VarDecl>(D);
4109 return CompleteObject();
4112 bool IsConstant = BaseType.
isConstant(Info.Ctx);
4117 if (IsAccess && isa<ParmVarDecl>(VD)) {
4121 }
else if (Info.getLangOpts().CPlusPlus14 &&
4128 Info.FFDiag(E, diag::note_constexpr_modify_global);
4129 return CompleteObject();
4135 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4136 if (Info.getLangOpts().CPlusPlus) {
4137 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4138 Info.Note(VD->
getLocation(), diag::note_declared_at);
4142 return CompleteObject();
4144 }
else if (!IsAccess) {
4145 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4146 }
else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4149 }
else if (IsConstant) {
4153 if (Info.getLangOpts().CPlusPlus) {
4154 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4155 ? diag::note_constexpr_ltor_non_constexpr
4156 : diag::note_constexpr_ltor_non_integral, 1)
4158 Info.Note(VD->
getLocation(), diag::note_declared_at);
4164 if (Info.getLangOpts().CPlusPlus) {
4165 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4166 ? diag::note_constexpr_ltor_non_constexpr
4167 : diag::note_constexpr_ltor_non_integral, 1)
4169 Info.Note(VD->
getLocation(), diag::note_declared_at);
4173 return CompleteObject();
4178 return CompleteObject();
4180 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4182 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4183 return CompleteObject();
4185 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4186 LVal.Base.getDynamicAllocType());
4192 dyn_cast_or_null<MaterializeTemporaryExpr>(
Base)) {
4193 assert(MTE->getStorageDuration() ==
SD_Static &&
4194 "should have a frame for a non-global materialized temporary");
4221 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4224 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4225 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4226 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4227 return CompleteObject();
4230 BaseVal = MTE->getOrCreateValue(
false);
4231 assert(BaseVal &&
"got reference to unevaluated temporary");
4234 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4237 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4240 Info.Ctx.getLValueReferenceType(LValType));
4242 return CompleteObject();
4245 BaseVal = Frame->getTemporary(
Base, LVal.Base.getVersion());
4246 assert(BaseVal &&
"missing value for temporary");
4257 unsigned VisibleDepth = Depth;
4258 if (llvm::isa_and_nonnull<ParmVarDecl>(
4259 LVal.Base.dyn_cast<
const ValueDecl *>()))
4261 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4262 Info.EvalStatus.HasSideEffects) ||
4263 (
isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4264 return CompleteObject();
4266 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4285 const LValue &LVal,
APValue &RVal,
4286 bool WantObjectRepresentation =
false) {
4287 if (LVal.Designator.Invalid)
4296 if (
Base && !LVal.getLValueCallIndex() && !
Type.isVolatileQualified()) {
4301 if (
Type.isVolatileQualified()) {
4307 if (!
Evaluate(Lit, Info, CLE->getInitializer()))
4327 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4332 CompleteObject LitObj(LVal.Base, &Lit,
Base->getType());
4334 }
else if (isa<StringLiteral>(
Base) || isa<PredefinedExpr>(
Base)) {
4337 assert(LVal.Designator.Entries.size() <= 1 &&
4338 "Can only read characters from string literals");
4339 if (LVal.Designator.Entries.empty()) {
4346 if (LVal.Designator.isOnePastTheEnd()) {
4347 if (Info.getLangOpts().CPlusPlus11)
4348 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4353 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4360 return Obj &&
extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4366 if (LVal.Designator.Invalid)
4369 if (!Info.getLangOpts().CPlusPlus14) {
4379struct CompoundAssignSubobjectHandler {
4388 typedef bool result_type;
4393 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4399 bool failed() {
return false; }
4403 return found(Subobj.
getInt(), SubobjType);
4405 return found(Subobj.
getFloat(), SubobjType);
4412 return foundPointer(Subobj, SubobjType);
4414 return foundVector(Subobj, SubobjType);
4416 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4428 if (!checkConst(SubobjType))
4439 if (!checkConst(SubobjType))
4458 Info.Ctx.getLangOpts());
4461 PromotedLHSType, FValue) &&
4471 return checkConst(SubobjType) &&
4478 if (!checkConst(SubobjType))
4486 (Opcode != BO_Add && Opcode != BO_Sub)) {
4492 if (Opcode == BO_Sub)
4496 LVal.setFrom(Info.Ctx, Subobj);
4499 LVal.moveInto(Subobj);
4505const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4510 const LValue &LVal,
QualType LValType,
4514 if (LVal.Designator.Invalid)
4517 if (!Info.getLangOpts().CPlusPlus14) {
4523 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4525 return Obj &&
findSubobject(Info, E, Obj, LVal.Designator, Handler);
4529struct IncDecSubobjectHandler {
4535 typedef bool result_type;
4540 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4546 bool failed() {
return false; }
4557 return found(Subobj.
getInt(), SubobjType);
4559 return found(Subobj.
getFloat(), SubobjType);
4569 return foundPointer(Subobj, SubobjType);
4577 if (!checkConst(SubobjType))
4599 bool WasNegative =
Value.isNegative();
4611 unsigned BitWidth =
Value.getBitWidth();
4612 APSInt ActualValue(
Value.sext(BitWidth + 1),
false);
4613 ActualValue.setBit(BitWidth);
4620 if (!checkConst(SubobjType))
4627 APFloat::opStatus St;
4629 St =
Value.add(One, RM);
4631 St =
Value.subtract(One, RM);
4635 if (!checkConst(SubobjType))
4647 LVal.setFrom(Info.Ctx, Subobj);
4651 LVal.moveInto(Subobj);
4660 if (LVal.Designator.Invalid)
4663 if (!Info.getLangOpts().CPlusPlus14) {
4670 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4671 return Obj &&
findSubobject(Info, E, Obj, LVal.Designator, Handler);
4677 if (Object->getType()->isPointerType() && Object->isPRValue())
4680 if (Object->isGLValue())
4683 if (Object->getType()->isLiteralType(Info.Ctx))
4686 if (Object->getType()->isRecordType() && Object->isPRValue())
4689 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4708 bool IncludeMember =
true) {
4715 if (!MemPtr.getDecl()) {
4721 if (MemPtr.isDerivedMember()) {
4725 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4726 LV.Designator.Entries.size()) {
4730 unsigned PathLengthToMember =
4731 LV.Designator.Entries.size() - MemPtr.Path.size();
4732 for (
unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4734 LV.Designator.Entries[PathLengthToMember + I]);
4744 PathLengthToMember))
4746 }
else if (!MemPtr.Path.empty()) {
4748 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4749 MemPtr.Path.size() + IncludeMember);
4755 assert(RD &&
"member pointer access on non-class-type expression");
4757 for (
unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4765 MemPtr.getContainingRecord()))
4770 if (IncludeMember) {
4771 if (
const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4775 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4779 llvm_unreachable(
"can't construct reference to bound member function");
4783 return MemPtr.getDecl();
4789 bool IncludeMember =
true) {
4793 if (Info.noteFailure()) {
4801 BO->
getRHS(), IncludeMember);
4808 SubobjectDesignator &D = Result.Designator;
4809 if (D.Invalid || !Result.checkNullPointer(Info, E,
CSK_Derived))
4817 if (D.MostDerivedPathLength + E->
path_size() > D.Entries.size()) {
4818 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4819 << D.MostDerivedType << TargetQT;
4825 unsigned NewEntriesSize = D.Entries.size() - E->
path_size();
4828 if (NewEntriesSize == D.MostDerivedPathLength)
4829 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4831 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4833 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4834 << D.MostDerivedType << TargetQT;
4845 bool Success =
true;
4848 if (!Result.isAbsent())
4852 if (RD->isInvalidDecl()) {
4856 if (RD->isUnion()) {
4861 std::distance(RD->field_begin(), RD->field_end()));
4865 End = RD->bases_end();
4866 I != End; ++I, ++Index)
4870 for (
const auto *I : RD->fields()) {
4871 if (I->isUnnamedBitfield())
4874 I->getType(), Result.getStructField(I->getFieldIndex()));
4882 if (Result.hasArrayFiller())
4894enum EvalStmtResult {
4918 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->
getType(),
4919 ScopeKind::Block, Result);
4924 return Info.noteSideEffect();
4943 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
4947 for (
auto *BD : DD->bindings())
4948 if (
auto *VD = BD->getHoldingVar())
4956 if (Info.noteSideEffect())
4958 assert(E->
containsErrors() &&
"valid value-dependent expression should never "
4959 "reach invalid code path.");
4965 const Expr *Cond,
bool &Result) {
4968 FullExpressionRAII
Scope(Info);
4973 return Scope.destroy();
4986struct TempVersionRAII {
4987 CallStackFrame &Frame;
4989 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4990 Frame.pushTempVersion();
4993 ~TempVersionRAII() {
4994 Frame.popTempVersion();
5008 BlockScopeRAII
Scope(Info);
5010 EvalStmtResult ESR =
EvaluateStmt(Result, Info, Body, Case);
5011 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !
Scope.destroy())
5016 return ESR_Succeeded;
5019 return ESR_Continue;
5022 case ESR_CaseNotFound:
5025 llvm_unreachable(
"Invalid EvalStmtResult!");
5031 BlockScopeRAII
Scope(Info);
5038 if (ESR != ESR_Succeeded) {
5039 if (ESR != ESR_Failed && !
Scope.destroy())
5045 FullExpressionRAII CondScope(Info);
5057 if (!CondScope.destroy())
5066 if (isa<DefaultStmt>(SC)) {
5071 const CaseStmt *CS = cast<CaseStmt>(SC);
5082 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5086 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !
Scope.destroy())
5091 return ESR_Succeeded;
5097 case ESR_CaseNotFound:
5101 diag::note_constexpr_stmt_expr_unsupported);
5104 llvm_unreachable(
"Invalid EvalStmtResult!");
5114 Info.CCEDiag(VD->
getLocation(), diag::note_constexpr_static_local)
5124 if (!Info.nextStep(S))
5130 switch (S->getStmtClass()) {
5131 case Stmt::CompoundStmtClass:
5135 case Stmt::LabelStmtClass:
5136 case Stmt::AttributedStmtClass:
5137 case Stmt::DoStmtClass:
5140 case Stmt::CaseStmtClass:
5141 case Stmt::DefaultStmtClass:
5146 case Stmt::IfStmtClass: {
5149 const IfStmt *IS = cast<IfStmt>(S);
5153 BlockScopeRAII
Scope(Info);
5159 if (ESR != ESR_CaseNotFound) {
5160 assert(ESR != ESR_Succeeded);
5171 if (ESR == ESR_Failed)
5173 if (ESR != ESR_CaseNotFound)
5174 return Scope.destroy() ? ESR : ESR_Failed;
5176 return ESR_CaseNotFound;
5179 if (ESR == ESR_Failed)
5181 if (ESR != ESR_CaseNotFound)
5182 return Scope.destroy() ? ESR : ESR_Failed;
5183 return ESR_CaseNotFound;
5186 case Stmt::WhileStmtClass: {
5187 EvalStmtResult ESR =
5189 if (ESR != ESR_Continue)
5194 case Stmt::ForStmtClass: {
5195 const ForStmt *FS = cast<ForStmt>(S);
5196 BlockScopeRAII
Scope(Info);
5200 if (
const Stmt *
Init = FS->getInit()) {
5202 if (ESR != ESR_CaseNotFound) {
5203 assert(ESR != ESR_Succeeded);
5208 EvalStmtResult ESR =
5210 if (ESR != ESR_Continue)
5212 if (
const auto *Inc = FS->getInc()) {
5213 if (Inc->isValueDependent()) {
5217 FullExpressionRAII IncScope(Info);
5225 case Stmt::DeclStmtClass: {
5228 const DeclStmt *DS = cast<DeclStmt>(S);
5229 for (
const auto *D : DS->
decls()) {
5230 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
5233 if (VD->hasLocalStorage() && !VD->getInit())
5241 return ESR_CaseNotFound;
5245 return ESR_CaseNotFound;
5249 switch (S->getStmtClass()) {
5251 if (
const Expr *E = dyn_cast<Expr>(S)) {
5260 FullExpressionRAII
Scope(Info);
5264 return ESR_Succeeded;
5267 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5270 case Stmt::NullStmtClass:
5271 return ESR_Succeeded;
5273 case Stmt::DeclStmtClass: {
5274 const DeclStmt *DS = cast<DeclStmt>(S);
5275 for (
const auto *D : DS->
decls()) {
5276 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5280 FullExpressionRAII
Scope(Info);
5283 if (!
Scope.destroy())
5286 return ESR_Succeeded;
5289 case Stmt::ReturnStmtClass: {
5290 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5291 FullExpressionRAII
Scope(Info);
5300 :
Evaluate(Result.Value, Info, RetExpr)))
5302 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5305 case Stmt::CompoundStmtClass: {
5306 BlockScopeRAII
Scope(Info);
5309 for (
const auto *BI : CS->
body()) {
5310 EvalStmtResult ESR =
EvaluateStmt(Result, Info, BI, Case);
5311 if (ESR == ESR_Succeeded)
5313 else if (ESR != ESR_CaseNotFound) {
5314 if (ESR != ESR_Failed && !
Scope.destroy())
5320 return ESR_CaseNotFound;
5321 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5324 case Stmt::IfStmtClass: {
5325 const IfStmt *IS = cast<IfStmt>(S);
5328 BlockScopeRAII
Scope(Info);
5331 if (ESR != ESR_Succeeded) {
5332 if (ESR != ESR_Failed && !
Scope.destroy())
5342 if (!Info.InConstantContext)
5349 EvalStmtResult ESR =
EvaluateStmt(Result, Info, SubStmt);
5350 if (ESR != ESR_Succeeded) {
5351 if (ESR != ESR_Failed && !
Scope.destroy())
5356 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5359 case Stmt::WhileStmtClass: {
5360 const WhileStmt *WS = cast<WhileStmt>(S);
5362 BlockScopeRAII
Scope(Info);
5371 if (ESR != ESR_Continue) {
5372 if (ESR != ESR_Failed && !
Scope.destroy())
5376 if (!
Scope.destroy())
5379 return ESR_Succeeded;
5382 case Stmt::DoStmtClass: {
5383 const DoStmt *DS = cast<DoStmt>(S);
5387 if (ESR != ESR_Continue)
5396 FullExpressionRAII CondScope(Info);
5398 !CondScope.destroy())
5401 return ESR_Succeeded;
5404 case Stmt::ForStmtClass: {
5405 const ForStmt *FS = cast<ForStmt>(S);
5406 BlockScopeRAII ForScope(Info);
5407 if (FS->getInit()) {
5408 EvalStmtResult ESR =
EvaluateStmt(Result, Info, FS->getInit());
5409 if (ESR != ESR_Succeeded) {
5410 if (ESR != ESR_Failed && !ForScope.destroy())
5416 BlockScopeRAII IterScope(Info);
5417 bool Continue =
true;
5418 if (FS->getCond() && !
EvaluateCond(Info, FS->getConditionVariable(),
5419 FS->getCond(), Continue))
5425 if (ESR != ESR_Continue) {
5426 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5431 if (
const auto *Inc = FS->getInc()) {
5432 if (Inc->isValueDependent()) {
5436 FullExpressionRAII IncScope(Info);
5442 if (!IterScope.destroy())
5445 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5448 case Stmt::CXXForRangeStmtClass: {
5450 BlockScopeRAII
Scope(Info);
5453 if (FS->getInit()) {
5454 EvalStmtResult ESR =
EvaluateStmt(Result, Info, FS->getInit());
5455 if (ESR != ESR_Succeeded) {
5456 if (ESR != ESR_Failed && !
Scope.destroy())
5463 EvalStmtResult ESR =
EvaluateStmt(Result, Info, FS->getRangeStmt());
5464 if (ESR != ESR_Succeeded) {
5465 if (ESR != ESR_Failed && !
Scope.destroy())
5472 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5477 if (ESR != ESR_Succeeded) {
5478 if (ESR != ESR_Failed && !
Scope.destroy())
5483 if (ESR != ESR_Succeeded) {
5484 if (ESR != ESR_Failed && !
Scope.destroy())
5492 if (FS->getCond()->isValueDependent()) {
5497 bool Continue =
true;
5498 FullExpressionRAII CondExpr(Info);
5506 BlockScopeRAII InnerScope(Info);
5507 ESR =
EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5508 if (ESR != ESR_Succeeded) {
5509 if (ESR != ESR_Failed && (!InnerScope.destroy() || !
Scope.destroy()))
5516 if (ESR != ESR_Continue) {
5517 if (ESR != ESR_Failed && (!InnerScope.destroy() || !
Scope.destroy()))
5521 if (FS->getInc()->isValueDependent()) {
5530 if (!InnerScope.destroy())
5534 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5537 case Stmt::SwitchStmtClass:
5540 case Stmt::ContinueStmtClass:
5541 return ESR_Continue;
5543 case Stmt::BreakStmtClass:
5546 case Stmt::LabelStmtClass:
5547 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5549 case Stmt::AttributedStmtClass:
5552 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5555 case Stmt::CaseStmtClass:
5556 case Stmt::DefaultStmtClass:
5557 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5558 case Stmt::CXXTryStmtClass:
5560 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5570 bool IsValueInitialization) {
5577 if (!CD->
isConstexpr() && !IsValueInitialization) {
5578 if (Info.getLangOpts().CPlusPlus11) {
5581 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5583 Info.Note(CD->
getLocation(), diag::note_declared_at);
5585 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5599 if (Info.checkingPotentialConstantExpression() && !