clang 18.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ExprConstShared.h"
36#include "Interp/Context.h"
37#include "Interp/Frame.h"
38#include "Interp/State.h"
39#include "clang/AST/APValue.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/TypeLoc.h"
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"
63#include <cstring>
64#include <functional>
65#include <optional>
66
67#define DEBUG_TYPE "exprconstant"
68
69using namespace clang;
70using llvm::APFixedPoint;
71using llvm::APInt;
72using llvm::APSInt;
73using llvm::APFloat;
74using llvm::FixedPointSemantics;
75
76namespace {
77 struct LValue;
78 class CallStackFrame;
79 class EvalInfo;
80
81 using SourceLocExprScopeGuard =
83
84 static QualType getType(APValue::LValueBase B) {
85 return B.getType();
86 }
87
88 /// Get an LValue path entry, which is known to not be an array index, as a
89 /// field declaration.
90 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91 return 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 a
94 /// base class declaration.
95 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Determine whether this LValue path entry for a base class names a virtual
99 /// base class.
100 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
101 return E.getAsBaseOrMember().getInt();
102 }
103
104 /// Given an expression, determine the type used to store the result of
105 /// evaluating that expression.
106 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
107 if (E->isPRValue())
108 return E->getType();
109 return Ctx.getLValueReferenceType(E->getType());
110 }
111
112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
115 return DirectCallee->getAttr<AllocSizeAttr>();
116 if (const Decl *IndirectCallee = CE->getCalleeDecl())
117 return IndirectCallee->getAttr<AllocSizeAttr>();
118 return nullptr;
119 }
120
121 /// 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.
125 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
126 if (!E->getType()->isPointerType())
127 return nullptr;
128
129 E = E->IgnoreParens();
130 // If we're doing a variable assignment from e.g. malloc(N), there will
131 // probably be a cast of some kind. In exotic cases, we might also see a
132 // top-level ExprWithCleanups. Ignore them either way.
133 if (const auto *FE = dyn_cast<FullExpr>(E))
134 E = FE->getSubExpr()->IgnoreParens();
135
136 if (const auto *Cast = dyn_cast<CastExpr>(E))
137 E = Cast->getSubExpr()->IgnoreParens();
138
139 if (const auto *CE = dyn_cast<CallExpr>(E))
140 return getAllocSizeAttr(CE) ? CE : nullptr;
141 return nullptr;
142 }
143
144 /// Determines whether or not the given Base contains a call to a function
145 /// with the alloc_size attribute.
146 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
147 const auto *E = Base.dyn_cast<const Expr *>();
148 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
149 }
150
151 /// Determines whether the given kind of constant expression is only ever
152 /// used for name mangling. If so, it's permitted to reference things that we
153 /// can't generate code for (in particular, dllimported functions).
154 static bool isForManglingOnly(ConstantExprKind Kind) {
155 switch (Kind) {
156 case ConstantExprKind::Normal:
157 case ConstantExprKind::ClassTemplateArgument:
158 case ConstantExprKind::ImmediateInvocation:
159 // Note that non-type template arguments of class type are emitted as
160 // template parameter objects.
161 return false;
162
163 case ConstantExprKind::NonClassTemplateArgument:
164 return true;
165 }
166 llvm_unreachable("unknown ConstantExprKind");
167 }
168
169 static bool isTemplateArgument(ConstantExprKind Kind) {
170 switch (Kind) {
171 case ConstantExprKind::Normal:
172 case ConstantExprKind::ImmediateInvocation:
173 return false;
174
175 case ConstantExprKind::ClassTemplateArgument:
176 case ConstantExprKind::NonClassTemplateArgument:
177 return true;
178 }
179 llvm_unreachable("unknown ConstantExprKind");
180 }
181
182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
187
188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
192 static unsigned
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&
200 "Unsized arrays shouldn't appear here");
201 unsigned MostDerivedLength = 0;
202 Type = getType(Base);
203
204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205 if (Type->isArrayType()) {
206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
208 MostDerivedLength = I + 1;
209 IsArray = true;
210
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
213 } else {
214 assert(I == 0 && "unexpected unsized array designator");
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
217 }
218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
221 ArraySize = 2;
222 MostDerivedLength = I + 1;
223 IsArray = true;
224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
226 ArraySize = 0;
227 MostDerivedLength = I + 1;
228 IsArray = false;
229 } else {
230 // Path[I] describes a base class.
231 ArraySize = 0;
232 IsArray = false;
233 }
234 }
235 return MostDerivedLength;
236 }
237
238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
243 unsigned Invalid : 1;
244
245 /// Is this a pointer one past the end of an object?
246 unsigned IsOnePastTheEnd : 1;
247
248 /// Indicator of whether the first entry is an unsized array.
249 unsigned FirstEntryIsAnUnsizedArray : 1;
250
251 /// Indicator of whether the most-derived object is an array element.
252 unsigned MostDerivedIsArrayElement : 1;
253
254 /// The length of the path to the most-derived object of which this is a
255 /// subobject.
256 unsigned MostDerivedPathLength : 28;
257
258 /// The size of the array of which the most-derived object is an element.
259 /// This will always be 0 if the most-derived object is not an array
260 /// element. 0 is not an indicator of whether or not the most-derived object
261 /// is an array, however, because 0-length arrays are allowed.
262 ///
263 /// If the current array is an unsized array, the value of this is
264 /// undefined.
265 uint64_t MostDerivedArraySize;
266
267 /// The type of the most derived object referred to by this address.
268 QualType MostDerivedType;
269
270 typedef APValue::LValuePathEntry PathEntry;
271
272 /// The entries on the path from the glvalue to the designated subobject.
274
275 SubobjectDesignator() : Invalid(true) {}
276
277 explicit SubobjectDesignator(QualType T)
278 : Invalid(false), IsOnePastTheEnd(false),
279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
282
283 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
288 if (!Invalid) {
289 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
290 ArrayRef<PathEntry> VEntries = V.getLValuePath();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292 if (V.getLValueBase()) {
293 bool IsArray = false;
294 bool FirstIsUnsizedArray = false;
295 MostDerivedPathLength = findMostDerivedSubobject(
296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
297 MostDerivedType, IsArray, FirstIsUnsizedArray);
298 MostDerivedIsArrayElement = IsArray;
299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
300 }
301 }
302 }
303
304 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305 unsigned NewLength) {
306 if (Invalid)
307 return;
308
309 assert(Base && "cannot truncate path for null pointer");
310 assert(NewLength <= Entries.size() && "not a truncation");
311
312 if (NewLength == Entries.size())
313 return;
314 Entries.resize(NewLength);
315
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;
323 }
324
325 void setInvalid() {
326 Invalid = true;
327 Entries.clear();
328 }
329
330 /// Determine whether the most derived subobject is an array without a
331 /// known bound.
332 bool isMostDerivedAnUnsizedArray() const {
333 assert(!Invalid && "Calling this makes no sense on invalid designators");
334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
335 }
336
337 /// Determine what the most derived array's size is. Results in an assertion
338 /// failure if the most derived array lacks a size.
339 uint64_t getMostDerivedArraySize() const {
340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341 return MostDerivedArraySize;
342 }
343
344 /// Determine whether this is a one-past-the-end pointer.
345 bool isOnePastTheEnd() const {
346 assert(!Invalid);
347 if (IsOnePastTheEnd)
348 return true;
349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
352 return true;
353 return false;
354 }
355
356 /// Get the range of valid index adjustments in the form
357 /// {maximum value that can be subtracted from this pointer,
358 /// maximum value that can be added to this pointer}
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
361 return {0, 0};
362
363 // [expr.add]p4: For the purposes of these operators, a pointer to a
364 // nonarray object behaves the same as a pointer to the first element of
365 // an array of length one with the type of the object as its element type.
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
370 uint64_t ArraySize =
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
373 }
374
375 /// Check that this refers to a valid subobject.
376 bool isValidSubobject() const {
377 if (Invalid)
378 return false;
379 return !isOnePastTheEnd();
380 }
381 /// Check that this refers to a valid subobject, and if not, produce a
382 /// relevant diagnostic and set the designator as invalid.
383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384
385 /// Get the type of the designated object.
386 QualType getType(ASTContext &Ctx) const {
387 assert(!Invalid && "invalid designator has no subobject type");
388 return MostDerivedPathLength == Entries.size()
389 ? MostDerivedType
390 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391 }
392
393 /// Update this designator to refer to the first element within this array.
394 void addArrayUnchecked(const ConstantArrayType *CAT) {
395 Entries.push_back(PathEntry::ArrayIndex(0));
396
397 // This is a most-derived object.
398 MostDerivedType = CAT->getElementType();
399 MostDerivedIsArrayElement = true;
400 MostDerivedArraySize = CAT->getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
402 }
403 /// Update this designator to refer to the first element within the array of
404 /// elements of type T. This is an array of unknown size.
405 void addUnsizedArrayUnchecked(QualType ElemTy) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
407
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement = true;
410 // The value in MostDerivedArraySize is undefined in this case. So, set it
411 // to an arbitrary value that's likely to loudly break things if it's
412 // used.
413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
414 MostDerivedPathLength = Entries.size();
415 }
416 /// Update this designator to refer to the given base or member of this
417 /// object.
418 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
420
421 // If this isn't a base class, it's a new most-derived object.
422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
424 MostDerivedIsArrayElement = false;
425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
427 }
428 }
429 /// Update this designator to refer to the given complex component.
430 void addComplexUnchecked(QualType EltTy, bool Imag) {
431 Entries.push_back(PathEntry::ArrayIndex(Imag));
432
433 // This is technically a most-derived object, though in practice this
434 // is unlikely to matter.
435 MostDerivedType = EltTy;
436 MostDerivedIsArrayElement = true;
437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
439 }
440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442 const APSInt &N);
443 /// Add N to the address of this subobject.
444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445 if (Invalid || !N) return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
449 // Can't verify -- trust that the user is doing the right thing (or if
450 // not, trust that the caller will catch the bad behavior).
451 // FIXME: Should we reject if this overflows, at least?
452 Entries.back() = PathEntry::ArrayIndex(
453 Entries.back().getAsArrayIndex() + TruncatedN);
454 return;
455 }
456
457 // [expr.add]p4: For the purposes of these operators, a pointer to a
458 // nonarray object behaves the same as a pointer to the first element of
459 // an array of length one with the type of the object as its element type.
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
464 uint64_t ArraySize =
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468 // Calculate the actual index in a wide enough type, so we can include
469 // it in the note.
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);
474 setInvalid();
475 return;
476 }
477
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&
480 "bounds check succeeded for out-of-bounds index");
481
482 if (IsArray)
483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
484 else
485 IsOnePastTheEnd = (ArrayIndex != 0);
486 }
487 };
488
489 /// A scope at the end of which an object can need to be destroyed.
490 enum class ScopeKind {
491 Block,
492 FullExpression,
493 Call
494 };
495
496 /// A reference to a particular call and its arguments.
497 struct CallRef {
498 CallRef() : OrigCallee(), CallIndex(0), Version() {}
499 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
500 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
501
502 explicit operator bool() const { return OrigCallee; }
503
504 /// Get the parameter that the caller initialized, corresponding to the
505 /// given parameter in the callee.
506 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
507 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
508 : PVD;
509 }
510
511 /// The callee at the point where the arguments were evaluated. This might
512 /// be different from the actual callee (a different redeclaration, or a
513 /// virtual override), but this function's parameters are the ones that
514 /// appear in the parameter map.
515 const FunctionDecl *OrigCallee;
516 /// The call index of the frame that holds the argument values.
517 unsigned CallIndex;
518 /// The version of the parameters corresponding to this call.
519 unsigned Version;
520 };
521
522 /// A stack frame in the constexpr call stack.
523 class CallStackFrame : public interp::Frame {
524 public:
525 EvalInfo &Info;
526
527 /// Parent - The caller of this stack frame.
528 CallStackFrame *Caller;
529
530 /// Callee - The function which was called.
531 const FunctionDecl *Callee;
532
533 /// This - The binding for the this pointer in this call, if any.
534 const LValue *This;
535
536 /// CallExpr - The syntactical structure of member function calls
537 const Expr *CallExpr;
538
539 /// Information on how to find the arguments to this call. Our arguments
540 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
541 /// key and this value as the version.
542 CallRef Arguments;
543
544 /// Source location information about the default argument or default
545 /// initializer expression we're evaluating, if any.
546 CurrentSourceLocExprScope CurSourceLocExprScope;
547
548 // Note that we intentionally use std::map here so that references to
549 // values are stable.
550 typedef std::pair<const void *, unsigned> MapKeyTy;
551 typedef std::map<MapKeyTy, APValue> MapTy;
552 /// Temporaries - Temporary lvalues materialized within this stack frame.
553 MapTy Temporaries;
554
555 /// CallRange - The source range of the call expression for this call.
556 SourceRange CallRange;
557
558 /// Index - The call index of this call.
559 unsigned Index;
560
561 /// The stack of integers for tracking version numbers for temporaries.
562 SmallVector<unsigned, 2> TempVersionStack = {1};
563 unsigned CurTempVersion = TempVersionStack.back();
564
565 unsigned getTempVersion() const { return TempVersionStack.back(); }
566
567 void pushTempVersion() {
568 TempVersionStack.push_back(++CurTempVersion);
569 }
570
571 void popTempVersion() {
572 TempVersionStack.pop_back();
573 }
574
575 CallRef createCall(const FunctionDecl *Callee) {
576 return {Callee, Index, ++CurTempVersion};
577 }
578
579 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
580 // on the overall stack usage of deeply-recursing constexpr evaluations.
581 // (We should cache this map rather than recomputing it repeatedly.)
582 // But let's try this and see how it goes; we can look into caching the map
583 // as a later change.
584
585 /// LambdaCaptureFields - Mapping from captured variables/this to
586 /// corresponding data members in the closure class.
587 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
588 FieldDecl *LambdaThisCaptureField = nullptr;
589
590 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
591 const FunctionDecl *Callee, const LValue *This,
592 const Expr *CallExpr, CallRef Arguments);
593 ~CallStackFrame();
594
595 // Return the temporary for Key whose version number is Version.
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)
600 return &LB->second;
601 return nullptr;
602 }
603
604 // Return the current temporary for Key in the map.
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;
609 return nullptr;
610 }
611
612 // Return the version number of the current temporary for Key.
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;
617 return 0;
618 }
619
620 /// Allocate storage for an object of type T in this stack frame.
621 /// Populates LV with a handle to the created object. Key identifies
622 /// the temporary within the stack frame, and must not be reused without
623 /// bumping the temporary version number.
624 template<typename KeyT>
625 APValue &createTemporary(const KeyT *Key, QualType T,
626 ScopeKind Scope, LValue &LV);
627
628 /// Allocate storage for a parameter of a function call made in this frame.
629 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
630
631 void describe(llvm::raw_ostream &OS) const override;
632
633 Frame *getCaller() const override { return Caller; }
634 SourceRange getCallRange() const override { return CallRange; }
635 const FunctionDecl *getCallee() const override { return Callee; }
636
637 bool isStdFunction() const {
638 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
639 if (DC->isStdNamespace())
640 return true;
641 return false;
642 }
643
644 private:
645 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
646 ScopeKind Scope);
647 };
648
649 /// Temporarily override 'this'.
650 class ThisOverrideRAII {
651 public:
652 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
653 : Frame(Frame), OldThis(Frame.This) {
654 if (Enable)
655 Frame.This = NewThis;
656 }
657 ~ThisOverrideRAII() {
658 Frame.This = OldThis;
659 }
660 private:
661 CallStackFrame &Frame;
662 const LValue *OldThis;
663 };
664
665 // A shorthand time trace scope struct, prints source range, for example
666 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
667 class ExprTimeTraceScope {
668 public:
669 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
670 : TimeScope(Name, [E, &Ctx] {
671 return E->getSourceRange().printToString(Ctx.getSourceManager());
672 }) {}
673
674 private:
675 llvm::TimeTraceScope TimeScope;
676 };
677}
678
679static bool HandleDestruction(EvalInfo &Info, const Expr *E,
680 const LValue &This, QualType ThisType);
681static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
683 QualType T);
684
685namespace {
686 /// A cleanup, and a flag indicating whether it is lifetime-extended.
687 class Cleanup {
688 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
690 QualType T;
691
692 public:
693 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
694 ScopeKind Scope)
695 : Value(Val, Scope), Base(Base), T(T) {}
696
697 /// Determine whether this cleanup should be performed at the end of the
698 /// given kind of scope.
699 bool isDestroyedAtEndOf(ScopeKind K) const {
700 return (int)Value.getInt() >= (int)K;
701 }
702 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
703 if (RunDestructors) {
704 SourceLocation Loc;
705 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
706 Loc = VD->getLocation();
707 else if (const Expr *E = Base.dyn_cast<const Expr*>())
708 Loc = E->getExprLoc();
709 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
710 }
711 *Value.getPointer() = APValue();
712 return true;
713 }
714
715 bool hasSideEffect() {
716 return T.isDestructedType();
717 }
718 };
719
720 /// A reference to an object whose construction we are currently evaluating.
721 struct ObjectUnderConstruction {
724 friend bool operator==(const ObjectUnderConstruction &LHS,
725 const ObjectUnderConstruction &RHS) {
726 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
727 }
728 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
729 return llvm::hash_combine(Obj.Base, Obj.Path);
730 }
731 };
732 enum class ConstructionPhase {
733 None,
734 Bases,
735 AfterBases,
736 AfterFields,
737 Destroying,
738 DestroyingBases
739 };
740}
741
742namespace llvm {
743template<> struct DenseMapInfo<ObjectUnderConstruction> {
744 using Base = DenseMapInfo<APValue::LValueBase>;
745 static ObjectUnderConstruction getEmptyKey() {
746 return {Base::getEmptyKey(), {}}; }
747 static ObjectUnderConstruction getTombstoneKey() {
748 return {Base::getTombstoneKey(), {}};
749 }
750 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
751 return hash_value(Object);
752 }
753 static bool isEqual(const ObjectUnderConstruction &LHS,
754 const ObjectUnderConstruction &RHS) {
755 return LHS == RHS;
756 }
757};
758}
759
760namespace {
761 /// A dynamically-allocated heap object.
762 struct DynAlloc {
763 /// The value of this heap-allocated object.
765 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
766 /// or a CallExpr (the latter is for direct calls to operator new inside
767 /// std::allocator<T>::allocate).
768 const Expr *AllocExpr = nullptr;
769
770 enum Kind {
771 New,
772 ArrayNew,
773 StdAllocator
774 };
775
776 /// Get the kind of the allocation. This must match between allocation
777 /// and deallocation.
778 Kind getKind() const {
779 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
780 return NE->isArray() ? ArrayNew : New;
781 assert(isa<CallExpr>(AllocExpr));
782 return StdAllocator;
783 }
784 };
785
786 struct DynAllocOrder {
787 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
788 return L.getIndex() < R.getIndex();
789 }
790 };
791
792 /// EvalInfo - This is a private struct used by the evaluator to capture
793 /// information about a subexpression as it is folded. It retains information
794 /// about the AST context, but also maintains information about the folded
795 /// expression.
796 ///
797 /// If an expression could be evaluated, it is still possible it is not a C
798 /// "integer constant expression" or constant expression. If not, this struct
799 /// captures information about how and why not.
800 ///
801 /// One bit of information passed *into* the request for constant folding
802 /// indicates whether the subexpression is "evaluated" or not according to C
803 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
804 /// evaluate the expression regardless of what the RHS is, but C only allows
805 /// certain things in certain situations.
806 class EvalInfo : public interp::State {
807 public:
808 ASTContext &Ctx;
809
810 /// EvalStatus - Contains information about the evaluation.
811 Expr::EvalStatus &EvalStatus;
812
813 /// CurrentCall - The top of the constexpr call stack.
814 CallStackFrame *CurrentCall;
815
816 /// CallStackDepth - The number of calls in the call stack right now.
817 unsigned CallStackDepth;
818
819 /// NextCallIndex - The next call index to assign.
820 unsigned NextCallIndex;
821
822 /// StepsLeft - The remaining number of evaluation steps we're permitted
823 /// to perform. This is essentially a limit for the number of statements
824 /// we will evaluate.
825 unsigned StepsLeft;
826
827 /// Enable the experimental new constant interpreter. If an expression is
828 /// not supported by the interpreter, an error is triggered.
829 bool EnableNewConstInterp;
830
831 /// BottomFrame - The frame in which evaluation started. This must be
832 /// initialized after CurrentCall and CallStackDepth.
833 CallStackFrame BottomFrame;
834
835 /// A stack of values whose lifetimes end at the end of some surrounding
836 /// evaluation frame.
838
839 /// EvaluatingDecl - This is the declaration whose initializer is being
840 /// evaluated, if any.
841 APValue::LValueBase EvaluatingDecl;
842
843 enum class EvaluatingDeclKind {
844 None,
845 /// We're evaluating the construction of EvaluatingDecl.
846 Ctor,
847 /// We're evaluating the destruction of EvaluatingDecl.
848 Dtor,
849 };
850 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
851
852 /// EvaluatingDeclValue - This is the value being constructed for the
853 /// declaration whose initializer is being evaluated, if any.
854 APValue *EvaluatingDeclValue;
855
856 /// Set of objects that are currently being constructed.
857 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
858 ObjectsUnderConstruction;
859
860 /// Current heap allocations, along with the location where each was
861 /// allocated. We use std::map here because we need stable addresses
862 /// for the stored APValues.
863 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
864
865 /// The number of heap allocations performed so far in this evaluation.
866 unsigned NumHeapAllocs = 0;
867
868 struct EvaluatingConstructorRAII {
869 EvalInfo &EI;
870 ObjectUnderConstruction Object;
871 bool DidInsert;
872 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
873 bool HasBases)
874 : EI(EI), Object(Object) {
875 DidInsert =
876 EI.ObjectsUnderConstruction
877 .insert({Object, HasBases ? ConstructionPhase::Bases
878 : ConstructionPhase::AfterBases})
879 .second;
880 }
881 void finishedConstructingBases() {
882 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
883 }
884 void finishedConstructingFields() {
885 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
886 }
887 ~EvaluatingConstructorRAII() {
888 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
889 }
890 };
891
892 struct EvaluatingDestructorRAII {
893 EvalInfo &EI;
894 ObjectUnderConstruction Object;
895 bool DidInsert;
896 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
897 : EI(EI), Object(Object) {
898 DidInsert = EI.ObjectsUnderConstruction
899 .insert({Object, ConstructionPhase::Destroying})
900 .second;
901 }
902 void startedDestroyingBases() {
903 EI.ObjectsUnderConstruction[Object] =
904 ConstructionPhase::DestroyingBases;
905 }
906 ~EvaluatingDestructorRAII() {
907 if (DidInsert)
908 EI.ObjectsUnderConstruction.erase(Object);
909 }
910 };
911
912 ConstructionPhase
913 isEvaluatingCtorDtor(APValue::LValueBase Base,
915 return ObjectsUnderConstruction.lookup({Base, Path});
916 }
917
918 /// If we're currently speculatively evaluating, the outermost call stack
919 /// depth at which we can mutate state, otherwise 0.
920 unsigned SpeculativeEvaluationDepth = 0;
921
922 /// The current array initialization index, if we're performing array
923 /// initialization.
924 uint64_t ArrayInitIndex = -1;
925
926 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
927 /// notes attached to it will also be stored, otherwise they will not be.
928 bool HasActiveDiagnostic;
929
930 /// Have we emitted a diagnostic explaining why we couldn't constant
931 /// fold (not just why it's not strictly a constant expression)?
932 bool HasFoldFailureDiagnostic;
933
934 /// Whether we're checking that an expression is a potential constant
935 /// expression. If so, do not fail on constructs that could become constant
936 /// later on (such as a use of an undefined global).
937 bool CheckingPotentialConstantExpression = false;
938
939 /// Whether we're checking for an expression that has undefined behavior.
940 /// If so, we will produce warnings if we encounter an operation that is
941 /// always undefined.
942 ///
943 /// Note that we still need to evaluate the expression normally when this
944 /// is set; this is used when evaluating ICEs in C.
945 bool CheckingForUndefinedBehavior = false;
946
947 enum EvaluationMode {
948 /// Evaluate as a constant expression. Stop if we find that the expression
949 /// is not a constant expression.
950 EM_ConstantExpression,
951
952 /// Evaluate as a constant expression. Stop if we find that the expression
953 /// is not a constant expression. Some expressions can be retried in the
954 /// optimizer if we don't constant fold them here, but in an unevaluated
955 /// context we try to fold them immediately since the optimizer never
956 /// gets a chance to look at it.
957 EM_ConstantExpressionUnevaluated,
958
959 /// Fold the expression to a constant. Stop if we hit a side-effect that
960 /// we can't model.
961 EM_ConstantFold,
962
963 /// Evaluate in any way we know how. Don't worry about side-effects that
964 /// can't be modeled.
965 EM_IgnoreSideEffects,
966 } EvalMode;
967
968 /// Are we checking whether the expression is a potential constant
969 /// expression?
970 bool checkingPotentialConstantExpression() const override {
971 return CheckingPotentialConstantExpression;
972 }
973
974 /// Are we checking an expression for overflow?
975 // FIXME: We should check for any kind of undefined or suspicious behavior
976 // in such constructs, not just overflow.
977 bool checkingForUndefinedBehavior() const override {
978 return CheckingForUndefinedBehavior;
979 }
980
981 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
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),
986 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
987 /*This=*/nullptr,
988 /*CallExpr=*/nullptr, CallRef()),
989 EvaluatingDecl((const ValueDecl *)nullptr),
990 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
991 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
992
993 ~EvalInfo() {
994 discardCleanups();
995 }
996
997 ASTContext &getCtx() const override { return Ctx; }
998
999 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1000 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1001 EvaluatingDecl = Base;
1002 IsEvaluatingDecl = EDK;
1003 EvaluatingDeclValue = &Value;
1004 }
1005
1006 bool CheckCallLimit(SourceLocation Loc) {
1007 // Don't perform any constexpr calls (other than the call we're checking)
1008 // when checking a potential constant expression.
1009 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1010 return false;
1011 if (NextCallIndex == 0) {
1012 // NextCallIndex has wrapped around.
1013 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1014 return false;
1015 }
1016 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1017 return true;
1018 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1019 << getLangOpts().ConstexprCallDepth;
1020 return false;
1021 }
1022
1023 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1024 uint64_t ElemCount, bool Diag) {
1025 // FIXME: GH63562
1026 // APValue stores array extents as unsigned,
1027 // so anything that is greater that unsigned would overflow when
1028 // constructing the array, we catch this here.
1029 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1030 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1031 if (Diag)
1032 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1033 return false;
1034 }
1035
1036 // FIXME: GH63562
1037 // Arrays allocate an APValue per element.
1038 // We use the number of constexpr steps as a proxy for the maximum size
1039 // of arrays to avoid exhausting the system resources, as initialization
1040 // of each element is likely to take some number of steps anyway.
1041 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1042 if (ElemCount > Limit) {
1043 if (Diag)
1044 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1045 << ElemCount << Limit;
1046 return false;
1047 }
1048 return true;
1049 }
1050
1051 std::pair<CallStackFrame *, unsigned>
1052 getCallFrameAndDepth(unsigned CallIndex) {
1053 assert(CallIndex && "no call index in getCallFrameAndDepth");
1054 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1055 // be null in this loop.
1056 unsigned Depth = CallStackDepth;
1057 CallStackFrame *Frame = CurrentCall;
1058 while (Frame->Index > CallIndex) {
1059 Frame = Frame->Caller;
1060 --Depth;
1061 }
1062 if (Frame->Index == CallIndex)
1063 return {Frame, Depth};
1064 return {nullptr, 0};
1065 }
1066
1067 bool nextStep(const Stmt *S) {
1068 if (!StepsLeft) {
1069 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1070 return false;
1071 }
1072 --StepsLeft;
1073 return true;
1074 }
1075
1076 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1077
1078 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1079 std::optional<DynAlloc *> Result;
1080 auto It = HeapAllocs.find(DA);
1081 if (It != HeapAllocs.end())
1082 Result = &It->second;
1083 return Result;
1084 }
1085
1086 /// Get the allocated storage for the given parameter of the given call.
1087 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1088 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1089 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1090 : nullptr;
1091 }
1092
1093 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1094 struct StdAllocatorCaller {
1095 unsigned FrameIndex;
1096 QualType ElemType;
1097 explicit operator bool() const { return FrameIndex != 0; };
1098 };
1099
1100 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1101 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1102 Call = Call->Caller) {
1103 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1104 if (!MD)
1105 continue;
1106 const IdentifierInfo *FnII = MD->getIdentifier();
1107 if (!FnII || !FnII->isStr(FnName))
1108 continue;
1109
1110 const auto *CTSD =
1111 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1112 if (!CTSD)
1113 continue;
1114
1115 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1116 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1117 if (CTSD->isInStdNamespace() && ClassII &&
1118 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1119 TAL[0].getKind() == TemplateArgument::Type)
1120 return {Call->Index, TAL[0].getAsType()};
1121 }
1122
1123 return {};
1124 }
1125
1126 void performLifetimeExtension() {
1127 // Disable the cleanups for lifetime-extended temporaries.
1128 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1129 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1130 });
1131 }
1132
1133 /// Throw away any remaining cleanups at the end of evaluation. If any
1134 /// cleanups would have had a side-effect, note that as an unmodeled
1135 /// side-effect and return false. Otherwise, return true.
1136 bool discardCleanups() {
1137 for (Cleanup &C : CleanupStack) {
1138 if (C.hasSideEffect() && !noteSideEffect()) {
1139 CleanupStack.clear();
1140 return false;
1141 }
1142 }
1143 CleanupStack.clear();
1144 return true;
1145 }
1146
1147 private:
1148 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1149 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1150
1151 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1152 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1153
1154 void setFoldFailureDiagnostic(bool Flag) override {
1155 HasFoldFailureDiagnostic = Flag;
1156 }
1157
1158 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1159
1160 // If we have a prior diagnostic, it will be noting that the expression
1161 // isn't a constant expression. This diagnostic is more important,
1162 // unless we require this evaluation to produce a constant expression.
1163 //
1164 // FIXME: We might want to show both diagnostics to the user in
1165 // EM_ConstantFold mode.
1166 bool hasPriorDiagnostic() override {
1167 if (!EvalStatus.Diag->empty()) {
1168 switch (EvalMode) {
1169 case EM_ConstantFold:
1170 case EM_IgnoreSideEffects:
1171 if (!HasFoldFailureDiagnostic)
1172 break;
1173 // We've already failed to fold something. Keep that diagnostic.
1174 [[fallthrough]];
1175 case EM_ConstantExpression:
1176 case EM_ConstantExpressionUnevaluated:
1177 setActiveDiagnostic(false);
1178 return true;
1179 }
1180 }
1181 return false;
1182 }
1183
1184 unsigned getCallStackDepth() override { return CallStackDepth; }
1185
1186 public:
1187 /// Should we continue evaluation after encountering a side-effect that we
1188 /// couldn't model?
1189 bool keepEvaluatingAfterSideEffect() {
1190 switch (EvalMode) {
1191 case EM_IgnoreSideEffects:
1192 return true;
1193
1194 case EM_ConstantExpression:
1195 case EM_ConstantExpressionUnevaluated:
1196 case EM_ConstantFold:
1197 // By default, assume any side effect might be valid in some other
1198 // evaluation of this expression from a different context.
1199 return checkingPotentialConstantExpression() ||
1200 checkingForUndefinedBehavior();
1201 }
1202 llvm_unreachable("Missed EvalMode case");
1203 }
1204
1205 /// Note that we have had a side-effect, and determine whether we should
1206 /// keep evaluating.
1207 bool noteSideEffect() {
1208 EvalStatus.HasSideEffects = true;
1209 return keepEvaluatingAfterSideEffect();
1210 }
1211
1212 /// Should we continue evaluation after encountering undefined behavior?
1213 bool keepEvaluatingAfterUndefinedBehavior() {
1214 switch (EvalMode) {
1215 case EM_IgnoreSideEffects:
1216 case EM_ConstantFold:
1217 return true;
1218
1219 case EM_ConstantExpression:
1220 case EM_ConstantExpressionUnevaluated:
1221 return checkingForUndefinedBehavior();
1222 }
1223 llvm_unreachable("Missed EvalMode case");
1224 }
1225
1226 /// Note that we hit something that was technically undefined behavior, but
1227 /// that we can evaluate past it (such as signed overflow or floating-point
1228 /// division by zero.)
1229 bool noteUndefinedBehavior() override {
1230 EvalStatus.HasUndefinedBehavior = true;
1231 return keepEvaluatingAfterUndefinedBehavior();
1232 }
1233
1234 /// Should we continue evaluation as much as possible after encountering a
1235 /// construct which can't be reduced to a value?
1236 bool keepEvaluatingAfterFailure() const override {
1237 if (!StepsLeft)
1238 return false;
1239
1240 switch (EvalMode) {
1241 case EM_ConstantExpression:
1242 case EM_ConstantExpressionUnevaluated:
1243 case EM_ConstantFold:
1244 case EM_IgnoreSideEffects:
1245 return checkingPotentialConstantExpression() ||
1246 checkingForUndefinedBehavior();
1247 }
1248 llvm_unreachable("Missed EvalMode case");
1249 }
1250
1251 /// Notes that we failed to evaluate an expression that other expressions
1252 /// directly depend on, and determine if we should keep evaluating. This
1253 /// should only be called if we actually intend to keep evaluating.
1254 ///
1255 /// Call noteSideEffect() instead if we may be able to ignore the value that
1256 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1257 ///
1258 /// (Foo(), 1) // use noteSideEffect
1259 /// (Foo() || true) // use noteSideEffect
1260 /// Foo() + 1 // use noteFailure
1261 [[nodiscard]] bool noteFailure() {
1262 // Failure when evaluating some expression often means there is some
1263 // subexpression whose evaluation was skipped. Therefore, (because we
1264 // don't track whether we skipped an expression when unwinding after an
1265 // evaluation failure) every evaluation failure that bubbles up from a
1266 // subexpression implies that a side-effect has potentially happened. We
1267 // skip setting the HasSideEffects flag to true until we decide to
1268 // continue evaluating after that point, which happens here.
1269 bool KeepGoing = keepEvaluatingAfterFailure();
1270 EvalStatus.HasSideEffects |= KeepGoing;
1271 return KeepGoing;
1272 }
1273
1274 class ArrayInitLoopIndex {
1275 EvalInfo &Info;
1276 uint64_t OuterIndex;
1277
1278 public:
1279 ArrayInitLoopIndex(EvalInfo &Info)
1280 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1281 Info.ArrayInitIndex = 0;
1282 }
1283 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1284
1285 operator uint64_t&() { return Info.ArrayInitIndex; }
1286 };
1287 };
1288
1289 /// Object used to treat all foldable expressions as constant expressions.
1290 struct FoldConstant {
1291 EvalInfo &Info;
1292 bool Enabled;
1293 bool HadNoPriorDiags;
1294 EvalInfo::EvaluationMode OldMode;
1295
1296 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1297 : Info(Info),
1298 Enabled(Enabled),
1299 HadNoPriorDiags(Info.EvalStatus.Diag &&
1300 Info.EvalStatus.Diag->empty() &&
1301 !Info.EvalStatus.HasSideEffects),
1302 OldMode(Info.EvalMode) {
1303 if (Enabled)
1304 Info.EvalMode = EvalInfo::EM_ConstantFold;
1305 }
1306 void keepDiagnostics() { Enabled = false; }
1307 ~FoldConstant() {
1308 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1309 !Info.EvalStatus.HasSideEffects)
1310 Info.EvalStatus.Diag->clear();
1311 Info.EvalMode = OldMode;
1312 }
1313 };
1314
1315 /// RAII object used to set the current evaluation mode to ignore
1316 /// side-effects.
1317 struct IgnoreSideEffectsRAII {
1318 EvalInfo &Info;
1319 EvalInfo::EvaluationMode OldMode;
1320 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1321 : Info(Info), OldMode(Info.EvalMode) {
1322 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1323 }
1324
1325 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1326 };
1327
1328 /// RAII object used to optionally suppress diagnostics and side-effects from
1329 /// a speculative evaluation.
1330 class SpeculativeEvaluationRAII {
1331 EvalInfo *Info = nullptr;
1332 Expr::EvalStatus OldStatus;
1333 unsigned OldSpeculativeEvaluationDepth = 0;
1334
1335 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1336 Info = Other.Info;
1337 OldStatus = Other.OldStatus;
1338 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1339 Other.Info = nullptr;
1340 }
1341
1342 void maybeRestoreState() {
1343 if (!Info)
1344 return;
1345
1346 Info->EvalStatus = OldStatus;
1347 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1348 }
1349
1350 public:
1351 SpeculativeEvaluationRAII() = default;
1352
1353 SpeculativeEvaluationRAII(
1354 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1355 : Info(&Info), OldStatus(Info.EvalStatus),
1356 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1357 Info.EvalStatus.Diag = NewDiag;
1358 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1359 }
1360
1361 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1362 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1363 moveFromAndCancel(std::move(Other));
1364 }
1365
1366 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1367 maybeRestoreState();
1368 moveFromAndCancel(std::move(Other));
1369 return *this;
1370 }
1371
1372 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1373 };
1374
1375 /// RAII object wrapping a full-expression or block scope, and handling
1376 /// the ending of the lifetime of temporaries created within it.
1377 template<ScopeKind Kind>
1378 class ScopeRAII {
1379 EvalInfo &Info;
1380 unsigned OldStackSize;
1381 public:
1382 ScopeRAII(EvalInfo &Info)
1383 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1384 // Push a new temporary version. This is needed to distinguish between
1385 // temporaries created in different iterations of a loop.
1386 Info.CurrentCall->pushTempVersion();
1387 }
1388 bool destroy(bool RunDestructors = true) {
1389 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1390 OldStackSize = -1U;
1391 return OK;
1392 }
1393 ~ScopeRAII() {
1394 if (OldStackSize != -1U)
1395 destroy(false);
1396 // Body moved to a static method to encourage the compiler to inline away
1397 // instances of this class.
1398 Info.CurrentCall->popTempVersion();
1399 }
1400 private:
1401 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1402 unsigned OldStackSize) {
1403 assert(OldStackSize <= Info.CleanupStack.size() &&
1404 "running cleanups out of order?");
1405
1406 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1407 // for a full-expression scope.
1408 bool Success = true;
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)) {
1412 Success = false;
1413 break;
1414 }
1415 }
1416 }
1417
1418 // Compact any retained cleanups.
1419 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1420 if (Kind != ScopeKind::Block)
1421 NewEnd =
1422 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1423 return C.isDestroyedAtEndOf(Kind);
1424 });
1425 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1426 return Success;
1427 }
1428 };
1429 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1430 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1431 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1432}
1433
1434bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1435 CheckSubobjectKind CSK) {
1436 if (Invalid)
1437 return false;
1438 if (isOnePastTheEnd()) {
1439 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1440 << CSK;
1441 setInvalid();
1442 return false;
1443 }
1444 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1445 // must actually be at least one array element; even a VLA cannot have a
1446 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1447 return true;
1448}
1449
1450void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1451 const Expr *E) {
1452 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1453 // Do not set the designator as invalid: we can represent this situation,
1454 // and correct handling of __builtin_object_size requires us to do so.
1455}
1456
1457void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1458 const Expr *E,
1459 const APSInt &N) {
1460 // If we're complaining, we must be able to statically determine the size of
1461 // the most derived array.
1462 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1463 Info.CCEDiag(E, diag::note_constexpr_array_index)
1464 << N << /*array*/ 0
1465 << static_cast<unsigned>(getMostDerivedArraySize());
1466 else
1467 Info.CCEDiag(E, diag::note_constexpr_array_index)
1468 << N << /*non-array*/ 1;
1469 setInvalid();
1470}
1471
1472CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1473 const FunctionDecl *Callee, const LValue *This,
1474 const Expr *CallExpr, CallRef Call)
1475 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1476 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1477 Index(Info.NextCallIndex++) {
1478 Info.CurrentCall = this;
1479 ++Info.CallStackDepth;
1480}
1481
1482CallStackFrame::~CallStackFrame() {
1483 assert(Info.CurrentCall == this && "calls retired out of order");
1484 --Info.CallStackDepth;
1485 Info.CurrentCall = Caller;
1486}
1487
1488static bool isRead(AccessKinds AK) {
1489 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1490}
1491
1493 switch (AK) {
1494 case AK_Read:
1496 case AK_MemberCall:
1497 case AK_DynamicCast:
1498 case AK_TypeId:
1499 return false;
1500 case AK_Assign:
1501 case AK_Increment:
1502 case AK_Decrement:
1503 case AK_Construct:
1504 case AK_Destroy:
1505 return true;
1506 }
1507 llvm_unreachable("unknown access kind");
1508}
1509
1510static bool isAnyAccess(AccessKinds AK) {
1511 return isRead(AK) || isModification(AK);
1512}
1513
1514/// Is this an access per the C++ definition?
1516 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1517}
1518
1519/// Is this kind of axcess valid on an indeterminate object value?
1521 switch (AK) {
1522 case AK_Read:
1523 case AK_Increment:
1524 case AK_Decrement:
1525 // These need the object's value.
1526 return false;
1527
1529 case AK_Assign:
1530 case AK_Construct:
1531 case AK_Destroy:
1532 // Construction and destruction don't need the value.
1533 return true;
1534
1535 case AK_MemberCall:
1536 case AK_DynamicCast:
1537 case AK_TypeId:
1538 // These aren't really meaningful on scalars.
1539 return true;
1540 }
1541 llvm_unreachable("unknown access kind");
1542}
1543
1544namespace {
1545 struct ComplexValue {
1546 private:
1547 bool IsInt;
1548
1549 public:
1550 APSInt IntReal, IntImag;
1551 APFloat FloatReal, FloatImag;
1552
1553 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1554
1555 void makeComplexFloat() { IsInt = false; }
1556 bool isComplexFloat() const { return !IsInt; }
1557 APFloat &getComplexFloatReal() { return FloatReal; }
1558 APFloat &getComplexFloatImag() { return FloatImag; }
1559
1560 void makeComplexInt() { IsInt = true; }
1561 bool isComplexInt() const { return IsInt; }
1562 APSInt &getComplexIntReal() { return IntReal; }
1563 APSInt &getComplexIntImag() { return IntImag; }
1564
1565 void moveInto(APValue &v) const {
1566 if (isComplexFloat())
1567 v = APValue(FloatReal, FloatImag);
1568 else
1569 v = APValue(IntReal, IntImag);
1570 }
1571 void setFrom(const APValue &v) {
1572 assert(v.isComplexFloat() || v.isComplexInt());
1573 if (v.isComplexFloat()) {
1574 makeComplexFloat();
1575 FloatReal = v.getComplexFloatReal();
1576 FloatImag = v.getComplexFloatImag();
1577 } else {
1578 makeComplexInt();
1579 IntReal = v.getComplexIntReal();
1580 IntImag = v.getComplexIntImag();
1581 }
1582 }
1583 };
1584
1585 struct LValue {
1587 CharUnits Offset;
1588 SubobjectDesignator Designator;
1589 bool IsNullPtr : 1;
1590 bool InvalidBase : 1;
1591
1592 const APValue::LValueBase getLValueBase() const { return Base; }
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;}
1598
1599 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1600 unsigned getLValueVersion() const { return Base.getVersion(); }
1601
1602 void moveInto(APValue &V) const {
1603 if (Designator.Invalid)
1604 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1605 else {
1606 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1607 V = APValue(Base, Offset, Designator.Entries,
1608 Designator.IsOnePastTheEnd, IsNullPtr);
1609 }
1610 }
1611 void setFrom(ASTContext &Ctx, const APValue &V) {
1612 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1613 Base = V.getLValueBase();
1614 Offset = V.getLValueOffset();
1615 InvalidBase = false;
1616 Designator = SubobjectDesignator(Ctx, V);
1617 IsNullPtr = V.isNullPointer();
1618 }
1619
1620 void set(APValue::LValueBase B, bool BInvalid = false) {
1621#ifndef NDEBUG
1622 // We only allow a few types of invalid bases. Enforce that here.
1623 if (BInvalid) {
1624 const auto *E = B.get<const Expr *>();
1625 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1626 "Unexpected type of invalid base");
1627 }
1628#endif
1629
1630 Base = B;
1631 Offset = CharUnits::fromQuantity(0);
1632 InvalidBase = BInvalid;
1633 Designator = SubobjectDesignator(getType(B));
1634 IsNullPtr = false;
1635 }
1636
1637 void setNull(ASTContext &Ctx, QualType PointerTy) {
1638 Base = (const ValueDecl *)nullptr;
1639 Offset =
1641 InvalidBase = false;
1642 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1643 IsNullPtr = true;
1644 }
1645
1646 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1647 set(B, true);
1648 }
1649
1650 std::string toString(ASTContext &Ctx, QualType T) const {
1651 APValue Printable;
1652 moveInto(Printable);
1653 return Printable.getAsString(Ctx, T);
1654 }
1655
1656 private:
1657 // Check that this LValue is not based on a null pointer. If it is, produce
1658 // a diagnostic and mark the designator as invalid.
1659 template <typename GenDiagType>
1660 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1661 if (Designator.Invalid)
1662 return false;
1663 if (IsNullPtr) {
1664 GenDiag();
1665 Designator.setInvalid();
1666 return false;
1667 }
1668 return true;
1669 }
1670
1671 public:
1672 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1673 CheckSubobjectKind CSK) {
1674 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1675 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1676 });
1677 }
1678
1679 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1680 AccessKinds AK) {
1681 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1682 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1683 });
1684 }
1685
1686 // Check this LValue refers to an object. If not, set the designator to be
1687 // invalid and emit a diagnostic.
1688 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1689 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1690 Designator.checkSubobject(Info, E, CSK);
1691 }
1692
1693 void addDecl(EvalInfo &Info, const Expr *E,
1694 const Decl *D, bool Virtual = false) {
1695 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1696 Designator.addDeclUnchecked(D, Virtual);
1697 }
1698 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1699 if (!Designator.Entries.empty()) {
1700 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1701 Designator.setInvalid();
1702 return;
1703 }
1704 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1705 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1706 Designator.FirstEntryIsAnUnsizedArray = true;
1707 Designator.addUnsizedArrayUnchecked(ElemTy);
1708 }
1709 }
1710 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1711 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1712 Designator.addArrayUnchecked(CAT);
1713 }
1714 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1715 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1716 Designator.addComplexUnchecked(EltTy, Imag);
1717 }
1718 void clearIsNullPointer() {
1719 IsNullPtr = false;
1720 }
1721 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1722 const APSInt &Index, CharUnits ElementSize) {
1723 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1724 // but we're not required to diagnose it and it's valid in C++.)
1725 if (!Index)
1726 return;
1727
1728 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1729 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1730 // offsets.
1731 uint64_t Offset64 = Offset.getQuantity();
1732 uint64_t ElemSize64 = ElementSize.getQuantity();
1733 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1734 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1735
1736 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1737 Designator.adjustIndex(Info, E, Index);
1738 clearIsNullPointer();
1739 }
1740 void adjustOffset(CharUnits N) {
1741 Offset += N;
1742 if (N.getQuantity())
1743 clearIsNullPointer();
1744 }
1745 };
1746
1747 struct MemberPtr {
1748 MemberPtr() {}
1749 explicit MemberPtr(const ValueDecl *Decl)
1750 : DeclAndIsDerivedMember(Decl, false) {}
1751
1752 /// The member or (direct or indirect) field referred to by this member
1753 /// pointer, or 0 if this is a null member pointer.
1754 const ValueDecl *getDecl() const {
1755 return DeclAndIsDerivedMember.getPointer();
1756 }
1757 /// Is this actually a member of some type derived from the relevant class?
1758 bool isDerivedMember() const {
1759 return DeclAndIsDerivedMember.getInt();
1760 }
1761 /// Get the class which the declaration actually lives in.
1762 const CXXRecordDecl *getContainingRecord() const {
1763 return cast<CXXRecordDecl>(
1764 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1765 }
1766
1767 void moveInto(APValue &V) const {
1768 V = APValue(getDecl(), isDerivedMember(), Path);
1769 }
1770 void setFrom(const APValue &V) {
1771 assert(V.isMemberPointer());
1772 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1773 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1774 Path.clear();
1775 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1776 Path.insert(Path.end(), P.begin(), P.end());
1777 }
1778
1779 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1780 /// whether the member is a member of some class derived from the class type
1781 /// of the member pointer.
1782 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1783 /// Path - The path of base/derived classes from the member declaration's
1784 /// class (exclusive) to the class type of the member pointer (inclusive).
1786
1787 /// Perform a cast towards the class of the Decl (either up or down the
1788 /// hierarchy).
1789 bool castBack(const CXXRecordDecl *Class) {
1790 assert(!Path.empty());
1791 const CXXRecordDecl *Expected;
1792 if (Path.size() >= 2)
1793 Expected = Path[Path.size() - 2];
1794 else
1795 Expected = getContainingRecord();
1796 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1797 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1798 // if B does not contain the original member and is not a base or
1799 // derived class of the class containing the original member, the result
1800 // of the cast is undefined.
1801 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1802 // (D::*). We consider that to be a language defect.
1803 return false;
1804 }
1805 Path.pop_back();
1806 return true;
1807 }
1808 /// Perform a base-to-derived member pointer cast.
1809 bool castToDerived(const CXXRecordDecl *Derived) {
1810 if (!getDecl())
1811 return true;
1812 if (!isDerivedMember()) {
1813 Path.push_back(Derived);
1814 return true;
1815 }
1816 if (!castBack(Derived))
1817 return false;
1818 if (Path.empty())
1819 DeclAndIsDerivedMember.setInt(false);
1820 return true;
1821 }
1822 /// Perform a derived-to-base member pointer cast.
1823 bool castToBase(const CXXRecordDecl *Base) {
1824 if (!getDecl())
1825 return true;
1826 if (Path.empty())
1827 DeclAndIsDerivedMember.setInt(true);
1828 if (isDerivedMember()) {
1829 Path.push_back(Base);
1830 return true;
1831 }
1832 return castBack(Base);
1833 }
1834 };
1835
1836 /// Compare two member pointers, which are assumed to be of the same type.
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())
1841 return false;
1842 return LHS.Path == RHS.Path;
1843 }
1844}
1845
1846static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1847static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1848 const LValue &This, const Expr *E,
1849 bool AllowNonLiteralTypes = false);
1850static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1851 bool InvalidBaseOK = false);
1852static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1853 bool InvalidBaseOK = false);
1854static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1855 EvalInfo &Info);
1856static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1857static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1858static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1859 EvalInfo &Info);
1860static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1861static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1862static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1863 EvalInfo &Info);
1864static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1865static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1866 EvalInfo &Info);
1867
1868/// Evaluate an integer or fixed point expression into an APResult.
1869static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1870 EvalInfo &Info);
1871
1872/// Evaluate only a fixed point expression into an APResult.
1873static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1874 EvalInfo &Info);
1875
1876//===----------------------------------------------------------------------===//
1877// Misc utilities
1878//===----------------------------------------------------------------------===//
1879
1880/// Negate an APSInt in place, converting it to a signed form if necessary, and
1881/// preserving its value (by extending by up to one bit as needed).
1882static void negateAsSigned(APSInt &Int) {
1883 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1884 Int = Int.extend(Int.getBitWidth() + 1);
1885 Int.setIsSigned(true);
1886 }
1887 Int = -Int;
1888}
1889
1890template<typename KeyT>
1891APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1892 ScopeKind Scope, LValue &LV) {
1893 unsigned Version = getTempVersion();
1894 APValue::LValueBase Base(Key, Index, Version);
1895 LV.set(Base);
1896 return createLocal(Base, Key, T, Scope);
1897}
1898
1899/// Allocate storage for a parameter of a function call made in this frame.
1900APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1901 LValue &LV) {
1902 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1903 APValue::LValueBase Base(PVD, Index, Args.Version);
1904 LV.set(Base);
1905 // We always destroy parameters at the end of the call, even if we'd allow
1906 // them to live to the end of the full-expression at runtime, in order to
1907 // give portable results and match other compilers.
1908 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1909}
1910
1911APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1912 QualType T, ScopeKind Scope) {
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");
1917
1918 // If we're creating a local immediately in the operand of a speculative
1919 // evaluation, don't register a cleanup to be run outside the speculative
1920 // evaluation context, since we won't actually be able to initialize this
1921 // object.
1922 if (Index <= Info.SpeculativeEvaluationDepth) {
1923 if (T.isDestructedType())
1924 Info.noteSideEffect();
1925 } else {
1926 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1927 }
1928 return Result;
1929}
1930
1931APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1932 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1933 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1934 return nullptr;
1935 }
1936
1937 DynamicAllocLValue DA(NumHeapAllocs++);
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;
1944}
1945
1946/// Produce a string describing the given constexpr call.
1947void CallStackFrame::describe(raw_ostream &Out) const {
1948 unsigned ArgIndex = 0;
1949 bool IsMemberCall =
1950 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1951 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1952
1953 if (!IsMemberCall)
1954 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1955 /*Qualified=*/false);
1956
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, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1961 /*Indentation=*/0);
1962 if (Object->getType()->isPointerType())
1963 Out << "->";
1964 else
1965 Out << ".";
1966 } else if (const auto *OCE =
1967 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1968 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1969 Info.Ctx.getPrintingPolicy(),
1970 /*Indentation=*/0);
1971 Out << ".";
1972 } else {
1973 APValue Val;
1974 This->moveInto(Val);
1975 Val.printPretty(
1976 Out, Info.Ctx,
1977 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1978 Out << ".";
1979 }
1980 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1981 /*Qualified=*/false);
1982 IsMemberCall = false;
1983 }
1984
1985 Out << '(';
1986
1987 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1988 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1989 if (ArgIndex > (unsigned)IsMemberCall)
1990 Out << ", ";
1991
1992 const ParmVarDecl *Param = *I;
1993 APValue *V = Info.getParamSlot(Arguments, Param);
1994 if (V)
1995 V->printPretty(Out, Info.Ctx, Param->getType());
1996 else
1997 Out << "<...>";
1998
1999 if (ArgIndex == 0 && IsMemberCall)
2000 Out << "->" << *Callee << '(';
2001 }
2002
2003 Out << ')';
2004}
2005
2006/// Evaluate an expression to see if it had side-effects, and discard its
2007/// result.
2008/// \return \c true if the caller should keep evaluating.
2009static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2010 assert(!E->isValueDependent());
2011 APValue Scratch;
2012 if (!Evaluate(Scratch, Info, E))
2013 // We don't need the value, but we might have skipped a side effect here.
2014 return Info.noteSideEffect();
2015 return true;
2016}
2017
2018/// Should this call expression be treated as a no-op?
2019static bool IsNoOpCall(const CallExpr *E) {
2020 unsigned Builtin = E->getBuiltinCallee();
2021 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2022 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2023 Builtin == Builtin::BI__builtin_function_start);
2024}
2025
2027 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2028 // constant expression of pointer type that evaluates to...
2029
2030 // ... a null pointer value, or a prvalue core constant expression of type
2031 // std::nullptr_t.
2032 if (!B)
2033 return true;
2034
2035 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2036 // ... the address of an object with static storage duration,
2037 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2038 return VD->hasGlobalStorage();
2039 if (isa<TemplateParamObjectDecl>(D))
2040 return true;
2041 // ... the address of a function,
2042 // ... the address of a GUID [MS extension],
2043 // ... the address of an unnamed global constant
2044 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2045 }
2046
2047 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2048 return true;
2049
2050 const Expr *E = B.get<const Expr*>();
2051 switch (E->getStmtClass()) {
2052 default:
2053 return false;
2054 case Expr::CompoundLiteralExprClass: {
2055 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2056 return CLE->isFileScope() && CLE->isLValue();
2057 }
2058 case Expr::MaterializeTemporaryExprClass:
2059 // A materialized temporary might have been lifetime-extended to static
2060 // storage duration.
2061 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2062 // A string literal has static storage duration.
2063 case Expr::StringLiteralClass:
2064 case Expr::PredefinedExprClass:
2065 case Expr::ObjCStringLiteralClass:
2066 case Expr::ObjCEncodeExprClass:
2067 return true;
2068 case Expr::ObjCBoxedExprClass:
2069 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2070 case Expr::CallExprClass:
2071 return IsNoOpCall(cast<CallExpr>(E));
2072 // For GCC compatibility, &&label has static storage duration.
2073 case Expr::AddrLabelExprClass:
2074 return true;
2075 // A Block literal expression may be used as the initialization value for
2076 // Block variables at global or local static scope.
2077 case Expr::BlockExprClass:
2078 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2079 // The APValue generated from a __builtin_source_location will be emitted as a
2080 // literal.
2081 case Expr::SourceLocExprClass:
2082 return true;
2083 case Expr::ImplicitValueInitExprClass:
2084 // FIXME:
2085 // We can never form an lvalue with an implicit value initialization as its
2086 // base through expression evaluation, so these only appear in one case: the
2087 // implicit variable declaration we invent when checking whether a constexpr
2088 // constructor can produce a constant expression. We must assume that such
2089 // an expression might be a global lvalue.
2090 return true;
2091 }
2092}
2093
2094static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2095 return LVal.Base.dyn_cast<const ValueDecl*>();
2096}
2097
2098static bool IsLiteralLValue(const LValue &Value) {
2099 if (Value.getLValueCallIndex())
2100 return false;
2101 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2102 return E && !isa<MaterializeTemporaryExpr>(E);
2103}
2104
2105static bool IsWeakLValue(const LValue &Value) {
2107 return Decl && Decl->isWeak();
2108}
2109
2110static bool isZeroSized(const LValue &Value) {
2112 if (Decl && isa<VarDecl>(Decl)) {
2113 QualType Ty = Decl->getType();
2114 if (Ty->isArrayType())
2115 return Ty->isIncompleteType() ||
2116 Decl->getASTContext().getTypeSize(Ty) == 0;
2117 }
2118 return false;
2119}
2120
2121static bool HasSameBase(const LValue &A, const LValue &B) {
2122 if (!A.getLValueBase())
2123 return !B.getLValueBase();
2124 if (!B.getLValueBase())
2125 return false;
2126
2127 if (A.getLValueBase().getOpaqueValue() !=
2128 B.getLValueBase().getOpaqueValue())
2129 return false;
2130
2131 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2132 A.getLValueVersion() == B.getLValueVersion();
2133}
2134
2135static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2136 assert(Base && "no location for a null lvalue");
2137 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2138
2139 // For a parameter, find the corresponding call stack frame (if it still
2140 // exists), and point at the parameter of the function definition we actually
2141 // invoked.
2142 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2143 unsigned Idx = PVD->getFunctionScopeIndex();
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);
2149 break;
2150 }
2151 }
2152 }
2153
2154 if (VD)
2155 Info.Note(VD->getLocation(), diag::note_declared_at);
2156 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2157 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2158 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2159 // FIXME: Produce a note for dangling pointers too.
2160 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2161 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2162 diag::note_constexpr_dynamic_alloc_here);
2163 }
2164
2165 // We have no information to show for a typeid(T) object.
2166}
2167
2171};
2172
2173/// Materialized temporaries that we've already checked to determine if they're
2174/// initializsed by a constant expression.
2177
2179 EvalInfo &Info, SourceLocation DiagLoc,
2180 QualType Type, const APValue &Value,
2181 ConstantExprKind Kind,
2182 const FieldDecl *SubobjectDecl,
2183 CheckedTemporaries &CheckedTemps);
2184
2185/// Check that this reference or pointer core constant expression is a valid
2186/// value for an address or reference constant expression. Return true if we
2187/// can fold this expression, whether or not it's a constant expression.
2188static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2189 QualType Type, const LValue &LVal,
2190 ConstantExprKind Kind,
2191 CheckedTemporaries &CheckedTemps) {
2192 bool IsReferenceType = Type->isReferenceType();
2193
2194 APValue::LValueBase Base = LVal.getLValueBase();
2195 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2196
2197 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2198 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2199
2200 // Additional restrictions apply in a template argument. We only enforce the
2201 // C++20 restrictions here; additional syntactic and semantic restrictions
2202 // are applied elsewhere.
2203 if (isTemplateArgument(Kind)) {
2204 int InvalidBaseKind = -1;
2205 StringRef Ident;
2206 if (Base.is<TypeInfoLValue>())
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();
2216 }
2217
2218 if (InvalidBaseKind != -1) {
2219 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2220 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2221 << Ident;
2222 return false;
2223 }
2224 }
2225
2226 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2227 FD && FD->isImmediateFunction()) {
2228 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2229 << !Type->isAnyPointerType();
2230 Info.Note(FD->getLocation(), diag::note_declared_at);
2231 return false;
2232 }
2233
2234 // Check that the object is a global. Note that the fake 'this' object we
2235 // manufacture when checking potential constant expressions is conservatively
2236 // assumed to be global here.
2237 if (!IsGlobalLValue(Base)) {
2238 if (Info.getLangOpts().CPlusPlus11) {
2239 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2240 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2241 << BaseVD;
2242 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2243 if (VarD && VarD->isConstexpr()) {
2244 // Non-static local constexpr variables have unintuitive semantics:
2245 // constexpr int a = 1;
2246 // constexpr const int *p = &a;
2247 // ... is invalid because the address of 'a' is not constant. Suggest
2248 // adding a 'static' in this case.
2249 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2250 << VarD
2251 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2252 } else {
2253 NoteLValueLocation(Info, Base);
2254 }
2255 } else {
2256 Info.FFDiag(Loc);
2257 }
2258 // Don't allow references to temporaries to escape.
2259 return false;
2260 }
2261 assert((Info.checkingPotentialConstantExpression() ||
2262 LVal.getLValueCallIndex() == 0) &&
2263 "have call index for global lvalue");
2264
2265 if (Base.is<DynamicAllocLValue>()) {
2266 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2267 << IsReferenceType << !Designator.Entries.empty();
2268 NoteLValueLocation(Info, Base);
2269 return false;
2270 }
2271
2272 if (BaseVD) {
2273 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2274 // Check if this is a thread-local variable.
2275 if (Var->getTLSKind())
2276 // FIXME: Diagnostic!
2277 return false;
2278
2279 // A dllimport variable never acts like a constant, unless we're
2280 // evaluating a value for use only in name mangling.
2281 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2282 // FIXME: Diagnostic!
2283 return false;
2284
2285 // In CUDA/HIP device compilation, only device side variables have
2286 // constant addresses.
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>())
2295 return false;
2296 }
2297 }
2298 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2299 // __declspec(dllimport) must be handled very carefully:
2300 // We must never initialize an expression with the thunk in C++.
2301 // Doing otherwise would allow the same id-expression to yield
2302 // different addresses for the same function in different translation
2303 // units. However, this means that we must dynamically initialize the
2304 // expression with the contents of the import address table at runtime.
2305 //
2306 // The C language has no notion of ODR; furthermore, it has no notion of
2307 // dynamic initialization. This means that we are permitted to
2308 // perform initialization with the address of the thunk.
2309 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2310 FD->hasAttr<DLLImportAttr>())
2311 // FIXME: Diagnostic!
2312 return false;
2313 }
2314 } else if (const auto *MTE =
2315 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2316 if (CheckedTemps.insert(MTE).second) {
2317 QualType TempType = getType(Base);
2318 if (TempType.isDestructedType()) {
2319 Info.FFDiag(MTE->getExprLoc(),
2320 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2321 << TempType;
2322 return false;
2323 }
2324
2325 APValue *V = MTE->getOrCreateValue(false);
2326 assert(V && "evasluation result refers to uninitialised temporary");
2327 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2328 Info, MTE->getExprLoc(), TempType, *V, Kind,
2329 /*SubobjectDecl=*/nullptr, CheckedTemps))
2330 return false;
2331 }
2332 }
2333
2334 // Allow address constant expressions to be past-the-end pointers. This is
2335 // an extension: the standard requires them to point to an object.
2336 if (!IsReferenceType)
2337 return true;
2338
2339 // A reference constant expression must refer to an object.
2340 if (!Base) {
2341 // FIXME: diagnostic
2342 Info.CCEDiag(Loc);
2343 return true;
2344 }
2345
2346 // Does this refer one past the end of some object?
2347 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2348 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2349 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2350 NoteLValueLocation(Info, Base);
2351 }
2352
2353 return true;
2354}
2355
2356/// Member pointers are constant expressions unless they point to a
2357/// non-virtual dllimport member function.
2358static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2359 SourceLocation Loc,
2360 QualType Type,
2361 const APValue &Value,
2362 ConstantExprKind Kind) {
2363 const ValueDecl *Member = Value.getMemberPointerDecl();
2364 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2365 if (!FD)
2366 return true;
2367 if (FD->isImmediateFunction()) {
2368 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2369 Info.Note(FD->getLocation(), diag::note_declared_at);
2370 return false;
2371 }
2372 return isForManglingOnly(Kind) || FD->isVirtual() ||
2373 !FD->hasAttr<DLLImportAttr>();
2374}
2375
2376/// Check that this core constant expression is of literal type, and if not,
2377/// produce an appropriate diagnostic.
2378static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2379 const LValue *This = nullptr) {
2380 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2381 return true;
2382
2383 // C++1y: A constant initializer for an object o [...] may also invoke
2384 // constexpr constructors for o and its subobjects even if those objects
2385 // are of non-literal class types.
2386 //
2387 // C++11 missed this detail for aggregates, so classes like this:
2388 // struct foo_t { union { int i; volatile int j; } u; };
2389 // are not (obviously) initializable like so:
2390 // __attribute__((__require_constant_initialization__))
2391 // static const foo_t x = {{0}};
2392 // because "i" is a subobject with non-literal initialization (due to the
2393 // volatile member of the union). See:
2394 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2395 // Therefore, we use the C++1y behavior.
2396 if (This && Info.EvaluatingDecl == This->getLValueBase())
2397 return true;
2398
2399 // Prvalue constant expressions must be of literal types.
2400 if (Info.getLangOpts().CPlusPlus11)
2401 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2402 << E->getType();
2403 else
2404 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2405 return false;
2406}
2407
2409 EvalInfo &Info, SourceLocation DiagLoc,
2410 QualType Type, const APValue &Value,
2411 ConstantExprKind Kind,
2412 const FieldDecl *SubobjectDecl,
2413 CheckedTemporaries &CheckedTemps) {
2414 if (!Value.hasValue()) {
2415 if (SubobjectDecl) {
2416 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2417 << /*(name)*/ 1 << SubobjectDecl;
2418 Info.Note(SubobjectDecl->getLocation(),
2419 diag::note_constexpr_subobject_declared_here);
2420 } else {
2421 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2422 << /*of type*/ 0 << Type;
2423 }
2424 return false;
2425 }
2426
2427 // We allow _Atomic(T) to be initialized from anything that T can be
2428 // initialized from.
2429 if (const AtomicType *AT = Type->getAs<AtomicType>())
2430 Type = AT->getValueType();
2431
2432 // Core issue 1454: For a literal constant expression of array or class type,
2433 // each subobject of its value shall have been initialized by a constant
2434 // expression.
2435 if (Value.isArray()) {
2437 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2438 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2439 Value.getArrayInitializedElt(I), Kind,
2440 SubobjectDecl, CheckedTemps))
2441 return false;
2442 }
2443 if (!Value.hasArrayFiller())
2444 return true;
2445 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2446 Value.getArrayFiller(), Kind, SubobjectDecl,
2447 CheckedTemps);
2448 }
2449 if (Value.isUnion() && Value.getUnionField()) {
2450 return CheckEvaluationResult(
2451 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2452 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2453 }
2454 if (Value.isStruct()) {
2455 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2456 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2457 unsigned BaseIndex = 0;
2458 for (const CXXBaseSpecifier &BS : CD->bases()) {
2459 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2460 if (!BaseValue.hasValue()) {
2461 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2462 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2463 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2464 return false;
2465 }
2466 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2467 Kind, /*SubobjectDecl=*/nullptr,
2468 CheckedTemps))
2469 return false;
2470 ++BaseIndex;
2471 }
2472 }
2473 for (const auto *I : RD->fields()) {
2474 if (I->isUnnamedBitfield())
2475 continue;
2476
2477 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2478 Value.getStructField(I->getFieldIndex()), Kind,
2479 I, CheckedTemps))
2480 return false;
2481 }
2482 }
2483
2484 if (Value.isLValue() &&
2485 CERK == CheckEvaluationResultKind::ConstantExpression) {
2486 LValue LVal;
2487 LVal.setFrom(Info.Ctx, Value);
2488 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2489 CheckedTemps);
2490 }
2491
2492 if (Value.isMemberPointer() &&
2493 CERK == CheckEvaluationResultKind::ConstantExpression)
2494 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2495
2496 // Everything else is fine.
2497 return true;
2498}
2499
2500/// Check that this core constant expression value is a valid value for a
2501/// constant expression. If not, report an appropriate diagnostic. Does not
2502/// check that the expression is of literal type.
2503static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2504 QualType Type, const APValue &Value,
2505 ConstantExprKind Kind) {
2506 // Nothing to check for a constant expression of type 'cv void'.
2507 if (Type->isVoidType())
2508 return true;
2509
2510 CheckedTemporaries CheckedTemps;
2511 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2512 Info, DiagLoc, Type, Value, Kind,
2513 /*SubobjectDecl=*/nullptr, CheckedTemps);
2514}
2515
2516/// Check that this evaluated value is fully-initialized and can be loaded by
2517/// an lvalue-to-rvalue conversion.
2518static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2519 QualType Type, const APValue &Value) {
2520 CheckedTemporaries CheckedTemps;
2521 return CheckEvaluationResult(
2522 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2523 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2524}
2525
2526/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2527/// "the allocated storage is deallocated within the evaluation".
2528static bool CheckMemoryLeaks(EvalInfo &Info) {
2529 if (!Info.HeapAllocs.empty()) {
2530 // We can still fold to a constant despite a compile-time memory leak,
2531 // so long as the heap allocation isn't referenced in the result (we check
2532 // that in CheckConstantExpression).
2533 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2534 diag::note_constexpr_memory_leak)
2535 << unsigned(Info.HeapAllocs.size() - 1);
2536 }
2537 return true;
2538}
2539
2540static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2541 // A null base expression indicates a null pointer. These are always
2542 // evaluatable, and they are false unless the offset is zero.
2543 if (!Value.getLValueBase()) {
2544 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2545 Result = !Value.getLValueOffset().isZero();
2546 return true;
2547 }
2548
2549 // We have a non-null base. These are generally known to be true, but if it's
2550 // a weak declaration it can be null at runtime.
2551 Result = true;
2552 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2553 return !Decl || !Decl->isWeak();
2554}
2555
2556static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2557 // TODO: This function should produce notes if it fails.
2558 switch (Val.getKind()) {
2559 case APValue::None:
2561 return false;
2562 case APValue::Int:
2563 Result = Val.getInt().getBoolValue();
2564 return true;
2566 Result = Val.getFixedPoint().getBoolValue();
2567 return true;
2568 case APValue::Float:
2569 Result = !Val.getFloat().isZero();
2570 return true;
2572 Result = Val.getComplexIntReal().getBoolValue() ||
2573 Val.getComplexIntImag().getBoolValue();
2574 return true;
2576 Result = !Val.getComplexFloatReal().isZero() ||
2577 !Val.getComplexFloatImag().isZero();
2578 return true;
2579 case APValue::LValue:
2580 return EvalPointerValueAsBool(Val, Result);
2582 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2583 return false;
2584 }
2585 Result = Val.getMemberPointerDecl();
2586 return true;
2587 case APValue::Vector:
2588 case APValue::Array:
2589 case APValue::Struct:
2590 case APValue::Union:
2592 return false;
2593 }
2594
2595 llvm_unreachable("unknown APValue kind");
2596}
2597
2598static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2599 EvalInfo &Info) {
2600 assert(!E->isValueDependent());
2601 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2602 APValue Val;
2603 if (!Evaluate(Val, Info, E))
2604 return false;
2605 return HandleConversionToBool(Val, Result);
2606}
2607
2608template<typename T>
2609static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2610 const T &SrcValue, QualType DestType) {
2611 Info.CCEDiag(E, diag::note_constexpr_overflow)
2612 << SrcValue << DestType;
2613 return Info.noteUndefinedBehavior();
2614}
2615
2616static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2617 QualType SrcType, const APFloat &Value,
2618 QualType DestType, APSInt &Result) {
2619 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2620 // Determine whether we are converting to unsigned or signed.
2621 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2622
2623 Result = APSInt(DestWidth, !DestSigned);
2624 bool ignored;
2625 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2626 & APFloat::opInvalidOp)
2627 return HandleOverflow(Info, E, Value, DestType);
2628 return true;
2629}
2630
2631/// Get rounding mode to use in evaluation of the specified expression.
2632///
2633/// If rounding mode is unknown at compile time, still try to evaluate the
2634/// expression. If the result is exact, it does not depend on rounding mode.
2635/// So return "tonearest" mode instead of "dynamic".
2636static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2637 llvm::RoundingMode RM =
2638 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2639 if (RM == llvm::RoundingMode::Dynamic)
2640 RM = llvm::RoundingMode::NearestTiesToEven;
2641 return RM;
2642}
2643
2644/// Check if the given evaluation result is allowed for constant evaluation.
2645static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2646 APFloat::opStatus St) {
2647 // In a constant context, assume that any dynamic rounding mode or FP
2648 // exception state matches the default floating-point environment.
2649 if (Info.InConstantContext)
2650 return true;
2651
2652 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2653 if ((St & APFloat::opInexact) &&
2654 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2655 // Inexact result means that it depends on rounding mode. If the requested
2656 // mode is dynamic, the evaluation cannot be made in compile time.
2657 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2658 return false;
2659 }
2660
2661 if ((St != APFloat::opOK) &&
2662 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2664 FPO.getAllowFEnvAccess())) {
2665 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2666 return false;
2667 }
2668
2669 if ((St & APFloat::opStatus::opInvalidOp) &&
2671 // There is no usefully definable result.
2672 Info.FFDiag(E);
2673 return false;
2674 }
2675
2676 // FIXME: if:
2677 // - evaluation triggered other FP exception, and
2678 // - exception mode is not "ignore", and
2679 // - the expression being evaluated is not a part of global variable
2680 // initializer,
2681 // the evaluation probably need to be rejected.
2682 return true;
2683}
2684
2685static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2686 QualType SrcType, QualType DestType,
2687 APFloat &Result) {
2688 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2689 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2690 APFloat::opStatus St;
2691 APFloat Value = Result;
2692 bool ignored;
2693 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2694 return checkFloatingPointResult(Info, E, St);
2695}
2696
2697static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2698 QualType DestType, QualType SrcType,
2699 const APSInt &Value) {
2700 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2701 // Figure out if this is a truncate, extend or noop cast.
2702 // If the input is signed, do a sign extend, noop, or truncate.
2703 APSInt Result = Value.extOrTrunc(DestWidth);
2704 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2705 if (DestType->isBooleanType())
2706 Result = Value.getBoolValue();
2707 return Result;
2708}
2709
2710static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2711 const FPOptions FPO,
2712 QualType SrcType, const APSInt &Value,
2713 QualType DestType, APFloat &Result) {
2714 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2715 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2716 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2717 return checkFloatingPointResult(Info, E, St);
2718}
2719
2720static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2721 APValue &Value, const FieldDecl *FD) {
2722 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2723
2724 if (!Value.isInt()) {
2725 // Trying to store a pointer-cast-to-integer into a bitfield.
2726 // FIXME: In this case, we should provide the diagnostic for casting
2727 // a pointer to an integer.
2728 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2729 Info.FFDiag(E);
2730 return false;
2731 }
2732
2733 APSInt &Int = Value.getInt();
2734 unsigned OldBitWidth = Int.getBitWidth();
2735 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2736 if (NewBitWidth < OldBitWidth)
2737 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2738 return true;
2739}
2740
2741/// Perform the given integer operation, which is known to need at most BitWidth
2742/// bits, and check for overflow in the original type (if that type was not an
2743/// unsigned type).
2744template<typename Operation>
2745static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2746 const APSInt &LHS, const APSInt &RHS,
2747 unsigned BitWidth, Operation Op,
2748 APSInt &Result) {
2749 if (LHS.isUnsigned()) {
2750 Result = Op(LHS, RHS);
2751 return true;
2752 }
2753
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)
2760 << toString(Result, 10) << E->getType() << E->getSourceRange();
2761 return HandleOverflow(Info, E, Value, E->getType());
2762 }
2763 return true;
2764}
2765
2766/// Perform the given binary integer operation.
2767static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2768 const APSInt &LHS, BinaryOperatorKind Opcode,
2769 APSInt RHS, APSInt &Result) {
2770 bool HandleOverflowResult = true;
2771 switch (Opcode) {
2772 default:
2773 Info.FFDiag(E);
2774 return false;
2775 case BO_Mul:
2776 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2777 std::multiplies<APSInt>(), Result);
2778 case BO_Add:
2779 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2780 std::plus<APSInt>(), Result);
2781 case BO_Sub:
2782 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
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;
2787 case BO_Div:
2788 case BO_Rem:
2789 if (RHS == 0) {
2790 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2791 << E->getRHS()->getSourceRange();
2792 return false;
2793 }
2794 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2795 // this operation and gives the two's complement result.
2796 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2797 LHS.isMinSignedValue())
2798 HandleOverflowResult = HandleOverflow(
2799 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2800 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2801 return HandleOverflowResult;
2802 case BO_Shl: {
2803 if (Info.getLangOpts().OpenCL)
2804 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2805 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2806 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2807 RHS.isUnsigned());
2808 else if (RHS.isSigned() && RHS.isNegative()) {
2809 // During constant-folding, a negative shift is an opposite shift. Such
2810 // a shift is not a constant expression.
2811 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2812 RHS = -RHS;
2813 goto shift_right;
2814 }
2815 shift_left:
2816 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2817 // the shifted type.
2818 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2819 if (SA != RHS) {
2820 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2821 << RHS << E->getType() << LHS.getBitWidth();
2822 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2823 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2824 // operand, and must not overflow the corresponding unsigned type.
2825 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2826 // E1 x 2^E2 module 2^N.
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);
2831 }
2832 Result = LHS << SA;
2833 return true;
2834 }
2835 case BO_Shr: {
2836 if (Info.getLangOpts().OpenCL)
2837 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2838 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2839 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2840 RHS.isUnsigned());
2841 else if (RHS.isSigned() && RHS.isNegative()) {
2842 // During constant-folding, a negative shift is an opposite shift. Such a
2843 // shift is not a constant expression.
2844 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2845 RHS = -RHS;
2846 goto shift_left;
2847 }
2848 shift_right:
2849 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2850 // shifted type.
2851 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2852 if (SA != RHS)
2853 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2854 << RHS << E->getType() << LHS.getBitWidth();
2855 Result = LHS >> SA;
2856 return true;
2857 }
2858
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;
2865 case BO_Cmp:
2866 llvm_unreachable("BO_Cmp should be handled elsewhere");
2867 }
2868}
2869
2870/// Perform the given binary floating-point operation, in-place, on LHS.
2871static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2872 APFloat &LHS, BinaryOperatorKind Opcode,
2873 const APFloat &RHS) {
2874 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2875 APFloat::opStatus St;
2876 switch (Opcode) {
2877 default:
2878 Info.FFDiag(E);
2879 return false;
2880 case BO_Mul:
2881 St = LHS.multiply(RHS, RM);
2882 break;
2883 case BO_Add:
2884 St = LHS.add(RHS, RM);
2885 break;
2886 case BO_Sub:
2887 St = LHS.subtract(RHS, RM);
2888 break;
2889 case BO_Div:
2890 // [expr.mul]p4:
2891 // If the second operand of / or % is zero the behavior is undefined.
2892 if (RHS.isZero())
2893 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2894 St = LHS.divide(RHS, RM);
2895 break;
2896 }
2897
2898 // [expr.pre]p4:
2899 // If during the evaluation of an expression, the result is not
2900 // mathematically defined [...], the behavior is undefined.
2901 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2902 if (LHS.isNaN()) {
2903 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2904 return Info.noteUndefinedBehavior();
2905 }
2906
2907 return checkFloatingPointResult(Info, E, St);
2908}
2909
2910static bool handleLogicalOpForVector(const APInt &LHSValue,
2911 BinaryOperatorKind Opcode,
2912 const APInt &RHSValue, APInt &Result) {
2913 bool LHS = (LHSValue != 0);
2914 bool RHS = (RHSValue != 0);
2915
2916 if (Opcode == BO_LAnd)
2917 Result = LHS && RHS;
2918 else
2919 Result = LHS || RHS;
2920 return true;
2921}
2922static bool handleLogicalOpForVector(const APFloat &LHSValue,
2923 BinaryOperatorKind Opcode,
2924 const APFloat &RHSValue, APInt &Result) {
2925 bool LHS = !LHSValue.isZero();
2926 bool RHS = !RHSValue.isZero();
2927
2928 if (Opcode == BO_LAnd)
2929 Result = LHS && RHS;
2930 else
2931 Result = LHS || RHS;
2932 return true;
2933}
2934
2935static bool handleLogicalOpForVector(const APValue &LHSValue,
2936 BinaryOperatorKind Opcode,
2937 const APValue &RHSValue, APInt &Result) {
2938 // The result is always an int type, however operands match the first.
2939 if (LHSValue.getKind() == APValue::Int)
2940 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2941 RHSValue.getInt(), Result);
2942 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2943 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2944 RHSValue.getFloat(), Result);
2945}
2946
2947template <typename APTy>
2948static bool
2950 const APTy &RHSValue, APInt &Result) {
2951 switch (Opcode) {
2952 default:
2953 llvm_unreachable("unsupported binary operator");
2954 case BO_EQ:
2955 Result = (LHSValue == RHSValue);
2956 break;
2957 case BO_NE:
2958 Result = (LHSValue != RHSValue);
2959 break;
2960 case BO_LT:
2961 Result = (LHSValue < RHSValue);
2962 break;
2963 case BO_GT:
2964 Result = (LHSValue > RHSValue);
2965 break;
2966 case BO_LE:
2967 Result = (LHSValue <= RHSValue);
2968 break;
2969 case BO_GE:
2970 Result = (LHSValue >= RHSValue);
2971 break;
2972 }
2973
2974 // The boolean operations on these vector types use an instruction that
2975 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2976 // to -1 to make sure that we produce the correct value.
2977 Result.negate();
2978
2979 return true;
2980}
2981
2982static bool handleCompareOpForVector(const APValue &LHSValue,
2983 BinaryOperatorKind Opcode,
2984 const APValue &RHSValue, APInt &Result) {
2985 // The result is always an int type, however operands match the first.
2986 if (LHSValue.getKind() == APValue::Int)
2987 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2988 RHSValue.getInt(), Result);
2989 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2990 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2991 RHSValue.getFloat(), Result);
2992}
2993
2994// Perform binary operations for vector types, in place on the LHS.
2995static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2996 BinaryOperatorKind Opcode,
2997 APValue &LHSValue,
2998 const APValue &RHSValue) {
2999 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3000 "Operation not supported on vector types");
3001
3002 const auto *VT = E->getType()->castAs<VectorType>();
3003 unsigned NumElements = VT->getNumElements();
3004 QualType EltTy = VT->getElementType();
3005
3006 // In the cases (typically C as I've observed) where we aren't evaluating
3007 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3008 // just give up.
3009 if (!LHSValue.isVector()) {
3010 assert(LHSValue.isLValue() &&
3011 "A vector result that isn't a vector OR uncalculated LValue");
3012 Info.FFDiag(E);
3013 return false;
3014 }
3015
3016 assert(LHSValue.getVectorLength() == NumElements &&
3017 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3018
3019 SmallVector<APValue, 4> ResultElements;
3020
3021 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3022 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3023 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3024
3025 if (EltTy->isIntegerType()) {
3026 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3027 EltTy->isUnsignedIntegerType()};
3028 bool Success = true;
3029
3030 if (BinaryOperator::isLogicalOp(Opcode))
3031 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3032 else if (BinaryOperator::isComparisonOp(Opcode))
3033 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3034 else
3035 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3036 RHSElt.getInt(), EltResult);
3037
3038 if (!Success) {
3039 Info.FFDiag(E);
3040 return false;
3041 }
3042 ResultElements.emplace_back(EltResult);
3043
3044 } else if (EltTy->isFloatingType()) {
3045 assert(LHSElt.getKind() == APValue::Float &&
3046 RHSElt.getKind() == APValue::Float &&
3047 "Mismatched LHS/RHS/Result Type");
3048 APFloat LHSFloat = LHSElt.getFloat();
3049
3050 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3051 RHSElt.getFloat())) {
3052 Info.FFDiag(E);
3053 return false;
3054 }
3055
3056 ResultElements.emplace_back(LHSFloat);
3057 }
3058 }
3059
3060 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3061 return true;
3062}
3063
3064/// Cast an lvalue referring to a base subobject to a derived class, by
3065/// truncating the lvalue's path to the given length.
3066static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3067 const RecordDecl *TruncatedType,
3068 unsigned TruncatedElements) {
3069 SubobjectDesignator &D = Result.Designator;
3070
3071 // Check we actually point to a derived class object.
3072 if (TruncatedElements == D.Entries.size())
3073 return true;
3074 assert(TruncatedElements >= D.MostDerivedPathLength &&
3075 "not casting to a derived class");
3076 if (!Result.checkSubobject(Info, E, CSK_Derived))
3077 return false;
3078
3079 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3080 const RecordDecl *RD = TruncatedType;
3081 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3082 if (RD->isInvalidDecl()) return false;
3083 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3084 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3085 if (isVirtualBaseClass(D.Entries[I]))
3086 Result.Offset -= Layout.getVBaseClassOffset(Base);
3087 else
3088 Result.Offset -= Layout.getBaseClassOffset(Base);
3089 RD = Base;
3090 }
3091 D.Entries.resize(TruncatedElements);
3092 return true;
3093}
3094
3095static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3096 const CXXRecordDecl *Derived,
3097 const CXXRecordDecl *Base,
3098 const ASTRecordLayout *RL = nullptr) {
3099 if (!RL) {
3100 if (Derived->isInvalidDecl()) return false;
3101 RL = &Info.Ctx.getASTRecordLayout(Derived);
3102 }
3103
3104 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3105 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3106 return true;
3107}
3108
3109static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3110 const CXXRecordDecl *DerivedDecl,
3111 const CXXBaseSpecifier *Base) {
3112 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3113
3114 if (!Base->isVirtual())
3115 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3116
3117 SubobjectDesignator &D = Obj.Designator;
3118 if (D.Invalid)
3119 return false;
3120
3121 // Extract most-derived object and corresponding type.
3122 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3123 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3124 return false;
3125
3126 // Find the virtual base class.
3127 if (DerivedDecl->isInvalidDecl()) return false;
3128 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3129 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3130 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3131 return true;
3132}
3133
3134static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3135 QualType Type, LValue &Result) {
3136 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3137 PathE = E->path_end();
3138 PathI != PathE; ++PathI) {
3139 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3140 *PathI))
3141 return false;
3142 Type = (*PathI)->getType();
3143 }
3144 return true;
3145}
3146
3147/// Cast an lvalue referring to a derived class to a known base subobject.
3148static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3149 const CXXRecordDecl *DerivedRD,
3150 const CXXRecordDecl *BaseRD) {
3151 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3152 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3153 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3154 llvm_unreachable("Class must be derived from the passed in base class!");
3155
3156 for (CXXBasePathElement &Elem : Paths.front())
3157 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3158 return false;
3159 return true;
3160}
3161
3162/// Update LVal to refer to the given field, which must be a member of the type
3163/// currently described by LVal.
3164static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3165 const FieldDecl *FD,
3166 const ASTRecordLayout *RL = nullptr) {
3167 if (!RL) {
3168 if (FD->getParent()->isInvalidDecl()) return false;
3169 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3170 }
3171
3172 unsigned I = FD->getFieldIndex();
3173 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3174 LVal.addDecl(Info, E, FD);
3175 return true;
3176}
3177
3178/// Update LVal to refer to the given indirect field.
3179static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3180 LValue &LVal,
3181 const IndirectFieldDecl *IFD) {
3182 for (const auto *C : IFD->chain())
3183 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3184 return false;
3185 return true;
3186}
3187
3188enum class SizeOfType {
3189 SizeOf,
3190 DataSizeOf,
3191};
3192
3193/// Get the size of the given type in char units.
3194static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3195 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3196 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3197 // extension.
3198 if (Type->isVoidType() || Type->isFunctionType()) {
3199 Size = CharUnits::One();
3200 return true;
3201 }
3202
3203 if (Type->isDependentType()) {
3204 Info.FFDiag(Loc);
3205 return false;
3206 }
3207
3208 if (!Type->isConstantSizeType()) {
3209 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3210 // FIXME: Better diagnostic.
3211 Info.FFDiag(Loc);
3212 return false;
3213 }
3214
3215 if (SOT == SizeOfType::SizeOf)
3216 Size = Info.Ctx.getTypeSizeInChars(Type);
3217 else
3218 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3219 return true;
3220}
3221
3222/// Update a pointer value to model pointer arithmetic.
3223/// \param Info - Information about the ongoing evaluation.
3224/// \param E - The expression being evaluated, for diagnostic purposes.
3225/// \param LVal - The pointer value to be updated.
3226/// \param EltTy - The pointee type represented by LVal.
3227/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3228static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3229 LValue &LVal, QualType EltTy,
3230 APSInt Adjustment) {
3231 CharUnits SizeOfPointee;
3232 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3233 return false;
3234
3235 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3236 return true;
3237}
3238
3239static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3240 LValue &LVal, QualType EltTy,
3241 int64_t Adjustment) {
3242 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3243 APSInt::get(Adjustment));
3244}
3245
3246/// Update an lvalue to refer to a component of a complex number.
3247/// \param Info - Information about the ongoing evaluation.
3248/// \param LVal - The lvalue to be updated.
3249/// \param EltTy - The complex number's component type.
3250/// \param Imag - False for the real component, true for the imaginary.
3251static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3252 LValue &LVal, QualType EltTy,
3253 bool Imag) {
3254 if (Imag) {
3255 CharUnits SizeOfComponent;
3256 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3257 return false;
3258 LVal.Offset += SizeOfComponent;
3259 }
3260 LVal.addComplex(Info, E, EltTy, Imag);
3261 return true;
3262}
3263
3264/// Try to evaluate the initializer for a variable declaration.
3265///
3266/// \param Info Information about the ongoing evaluation.
3267/// \param E An expression to be used when printing diagnostics.
3268/// \param VD The variable whose initializer should be obtained.
3269/// \param Version The version of the variable within the frame.
3270/// \param Frame The frame in which the variable was created. Must be null
3271/// if this variable is not local to the evaluation.
3272/// \param Result Filled in with a pointer to the value of the variable.
3273static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3274 const VarDecl *VD, CallStackFrame *Frame,
3275 unsigned Version, APValue *&Result) {
3276 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3277
3278 // If this is a local variable, dig out its value.
3279 if (Frame) {
3280 Result = Frame->getTemporary(VD, Version);
3281 if (Result)
3282 return true;
3283
3284 if (!isa<ParmVarDecl>(VD)) {
3285 // Assume variables referenced within a lambda's call operator that were
3286 // not declared within the call operator are captures and during checking
3287 // of a potential constant expression, assume they are unknown constant
3288 // expressions.
3289 assert(isLambdaCallOperator(Frame->Callee) &&
3290 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3291 "missing value for local variable");
3292 if (Info.checkingPotentialConstantExpression())
3293 return false;
3294 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3295 // still reachable at all?
3296 Info.FFDiag(E->getBeginLoc(),
3297 diag::note_unimplemented_constexpr_lambda_feature_ast)
3298 << "captures not currently allowed";
3299 return false;
3300 }
3301 }
3302
3303 // If we're currently evaluating the initializer of this declaration, use that
3304 // in-flight value.
3305 if (Info.EvaluatingDecl == Base) {
3306 Result = Info.EvaluatingDeclValue;
3307 return true;
3308 }
3309
3310 if (isa<ParmVarDecl>(VD)) {
3311 // Assume parameters of a potential constant expression are usable in
3312 // constant expressions.
3313 if (!Info.checkingPotentialConstantExpression() ||
3314 !Info.CurrentCall->Callee ||
3315 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3316 if (Info.getLangOpts().CPlusPlus11) {
3317 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3318 << VD;
3319 NoteLValueLocation(Info, Base);
3320 } else {
3321 Info.FFDiag(E);
3322 }
3323 }
3324 return false;
3325 }
3326
3327 if (E->isValueDependent())
3328 return false;
3329
3330 // Dig out the initializer, and use the declaration which it's attached to.
3331 // FIXME: We should eventually check whether the variable has a reachable
3332 // initializing declaration.
3333 const Expr *Init = VD->getAnyInitializer(VD);
3334 if (!Init) {
3335 // Don't diagnose during potential constant expression checking; an
3336 // initializer might be added later.
3337 if (!Info.checkingPotentialConstantExpression()) {
3338 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3339 << VD;
3340 NoteLValueLocation(Info, Base);
3341 }
3342 return false;
3343 }
3344
3345 if (Init->isValueDependent()) {
3346 // The DeclRefExpr is not value-dependent, but the variable it refers to
3347 // has a value-dependent initializer. This should only happen in
3348 // constant-folding cases, where the variable is not actually of a suitable
3349 // type for use in a constant expression (otherwise the DeclRefExpr would
3350 // have been value-dependent too), so diagnose that.
3351 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
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)
3356 << VD << VD->getType();
3357 NoteLValueLocation(Info, Base);
3358 }
3359 return false;
3360 }
3361
3362 // Check that we can fold the initializer. In C++, we will have already done
3363 // this in the cases where it matters for conformance.
3364 if (!VD->evaluateValue()) {
3365 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3366 NoteLValueLocation(Info, Base);
3367 return false;
3368 }
3369
3370 // Check that the variable is actually usable in constant expressions. For a
3371 // const integral variable or a reference, we might have a non-constant
3372 // initializer that we can nonetheless evaluate the initializer for. Such
3373 // variables are not usable in constant expressions. In C++98, the
3374 // initializer also syntactically needs to be an ICE.
3375 //
3376 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3377 // expressions here; doing so would regress diagnostics for things like
3378 // reading from a volatile constexpr variable.
3379 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3380 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3381 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3382 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3383 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3384 NoteLValueLocation(Info, Base);
3385 }
3386
3387 // Never use the initializer of a weak variable, not even for constant
3388 // folding. We can't be sure that this is the definition that will be used.
3389 if (VD->isWeak()) {
3390 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3391 NoteLValueLocation(Info, Base);
3392 return false;
3393 }
3394
3395 Result = VD->getEvaluatedValue();
3396 return true;
3397}
3398
3399/// Get the base index of the given base class within an APValue representing
3400/// the given derived class.
3401static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3402 const CXXRecordDecl *Base) {
3403 Base = Base->getCanonicalDecl();
3404 unsigned Index = 0;
3406 E = Derived->bases_end(); I != E; ++I, ++Index) {
3407 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3408 return Index;
3409 }
3410
3411 llvm_unreachable("base class missing from derived class's bases list");
3412}
3413
3414/// Extract the value of a character from a string literal.
3415static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3416 uint64_t Index) {
3417 assert(!isa<SourceLocExpr>(Lit) &&
3418 "SourceLocExpr should have already been converted to a StringLiteral");
3419
3420 // FIXME: Support MakeStringConstant
3421 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3422 std::string Str;
3423 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3424 assert(Index <= Str.size() && "Index too large");
3425 return APSInt::getUnsigned(Str.c_str()[Index]);
3426 }
3427
3428 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3429 Lit = PE->getFunctionName();
3430 const StringLiteral *S = cast<StringLiteral>(Lit);
3431 const ConstantArrayType *CAT =
3432 Info.Ctx.getAsConstantArrayType(S->getType());
3433 assert(CAT && "string literal isn't an array");
3434 QualType CharType = CAT->getElementType();
3435 assert(CharType->isIntegerType() && "unexpected character type");
3436 APSInt Value(Info.Ctx.getTypeSize(CharType),
3437 CharType->isUnsignedIntegerType());
3438 if (Index < S->getLength())
3439 Value = S->getCodeUnit(Index);
3440 return Value;
3441}
3442
3443// Expand a string literal into an array of characters.
3444//
3445// FIXME: This is inefficient; we should probably introduce something similar
3446// to the LLVM ConstantDataArray to make this cheaper.
3447static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3448 APValue &Result,
3449 QualType AllocType = QualType()) {
3450 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3451 AllocType.isNull() ? S->getType() : AllocType);
3452 assert(CAT && "string literal isn't an array");
3453 QualType CharType = CAT->getElementType();
3454 assert(CharType->isIntegerType() && "unexpected character type");
3455
3456 unsigned Elts = CAT->getSize().getZExtValue();
3457 Result = APValue(APValue::UninitArray(),
3458 std::min(S->getLength(), Elts), Elts);
3459 APSInt Value(Info.Ctx.getTypeSize(CharType),
3460 CharType->isUnsignedIntegerType());
3461 if (Result.hasArrayFiller())
3462 Result.getArrayFiller() = APValue(Value);
3463 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3464 Value = S->getCodeUnit(I);
3465 Result.getArrayInitializedElt(I) = APValue(Value);
3466 }
3467}
3468
3469// Expand an array so that it has more than Index filled elements.
3470static void expandArray(APValue &Array, unsigned Index) {
3471 unsigned Size = Array.getArraySize();
3472 assert(Index < Size);
3473
3474 // Always at least double the number of elements for which we store a value.
3475 unsigned OldElts = Array.getArrayInitializedElts();
3476 unsigned NewElts = std::max(Index+1, OldElts * 2);
3477 NewElts = std::min(Size, std::max(NewElts, 8u));
3478
3479 // Copy the data across.
3480 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3481 for (unsigned I = 0; I != OldElts; ++I)
3482 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3483 for (unsigned I = OldElts; I != NewElts; ++I)
3484 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3485 if (NewValue.hasArrayFiller())
3486 NewValue.getArrayFiller() = Array.getArrayFiller();
3487 Array.swap(NewValue);
3488}
3489
3490/// Determine whether a type would actually be read by an lvalue-to-rvalue
3491/// conversion. If it's of class type, we may assume that the copy operation
3492/// is trivial. Note that this is never true for a union type with fields
3493/// (because the copy always "reads" the active member) and always true for
3494/// a non-class type.
3495static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3498 return !RD || isReadByLvalueToRvalueConversion(RD);
3499}
3501 // FIXME: A trivial copy of a union copies the object representation, even if
3502 // the union is empty.
3503 if (RD->isUnion())
3504 return !RD->field_empty();
3505 if (RD->isEmpty())
3506 return false;
3507
3508 for (auto *Field : RD->fields())
3509 if (!Field->isUnnamedBitfield() &&
3510 isReadByLvalueToRvalueConversion(Field->getType()))
3511 return true;
3512
3513 for (auto &BaseSpec : RD->bases())
3514 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3515 return true;
3516
3517 return false;
3518}
3519
3520/// Diagnose an attempt to read from any unreadable field within the specified
3521/// type, which might be a class type.
3522static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3523 QualType T) {
3525 if (!RD)
3526 return false;
3527
3528 if (!RD->hasMutableFields())
3529 return false;
3530
3531 for (auto *Field : RD->fields()) {
3532 // If we're actually going to read this field in some way, then it can't
3533 // be mutable. If we're in a union, then assigning to a mutable field
3534 // (even an empty one) can change the active member, so that's not OK.
3535 // FIXME: Add core issue number for the union case.
3536 if (Field->isMutable() &&
3537 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3538 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3539 Info.Note(Field->getLocation(), diag::note_declared_at);
3540 return true;
3541 }
3542
3543 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3544 return true;
3545 }
3546
3547 for (auto &BaseSpec : RD->bases())
3548 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3549 return true;
3550
3551 // All mutable fields were empty, and thus not actually read.
3552 return false;
3553}
3554
3555static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3557 bool MutableSubobject = false) {
3558 // A temporary or transient heap allocation we created.
3559 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3560 return true;
3561
3562 switch (Info.IsEvaluatingDecl) {
3563 case EvalInfo::EvaluatingDeclKind::None:
3564 return false;
3565
3566 case EvalInfo::EvaluatingDeclKind::Ctor:
3567 // The variable whose initializer we're evaluating.
3568 if (Info.EvaluatingDecl == Base)
3569 return true;
3570
3571 // A temporary lifetime-extended by the variable whose initializer we're
3572 // evaluating.
3573 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3574 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3575 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3576 return false;
3577
3578 case EvalInfo::EvaluatingDeclKind::Dtor:
3579 // C++2a [expr.const]p6:
3580 // [during constant destruction] the lifetime of a and its non-mutable
3581 // subobjects (but not its mutable subobjects) [are] considered to start
3582 // within e.
3583 if (MutableSubobject || Base != Info.EvaluatingDecl)
3584 return false;
3585 // FIXME: We can meaningfully extend this to cover non-const objects, but
3586 // we will need special handling: we should be able to access only
3587 // subobjects of such objects that are themselves declared const.
3588 QualType T = getType(Base);
3589 return T.isConstQualified() || T->isReferenceType();
3590 }
3591
3592 llvm_unreachable("unknown evaluating decl kind");
3593}
3594
3595static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3596 SourceLocation CallLoc = {}) {
3597 return Info.CheckArraySize(
3598 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3599 CAT->getNumAddressingBits(Info.Ctx), CAT->getSize().getZExtValue(),
3600 /*Diag=*/true);
3601}
3602
3603namespace {
3604/// A handle to a complete object (an object that is not a subobject of
3605/// another object).
3606struct CompleteObject {
3607 /// The identity of the object.
3609 /// The value of the complete object.
3610 APValue *Value;
3611 /// The type of the complete object.
3612 QualType Type;
3613
3614 CompleteObject() : Value(nullptr) {}
3616 : Base(Base), Value(Value), Type(Type) {}
3617
3618 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3619 // If this isn't a "real" access (eg, if it's just accessing the type
3620 // info), allow it. We assume the type doesn't change dynamically for
3621 // subobjects of constexpr objects (even though we'd hit UB here if it
3622 // did). FIXME: Is this right?
3623 if (!isAnyAccess(AK))
3624 return true;
3625
3626 // In C++14 onwards, it is permitted to read a mutable member whose
3627 // lifetime began within the evaluation.
3628 // FIXME: Should we also allow this in C++11?
3629 if (!Info.getLangOpts().CPlusPlus14)
3630 return false;
3631 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3632 }
3633
3634 explicit operator bool() const { return !Type.isNull(); }
3635};
3636} // end anonymous namespace
3637
3638static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3639 bool IsMutable = false) {
3640 // C++ [basic.type.qualifier]p1:
3641 // - A const object is an object of type const T or a non-mutable subobject
3642 // of a const object.
3643 if (ObjType.isConstQualified() && !IsMutable)
3644 SubobjType.addConst();
3645 // - A volatile object is an object of type const T or a subobject of a
3646 // volatile object.
3647 if (ObjType.isVolatileQualified())
3648 SubobjType.addVolatile();
3649 return SubobjType;
3650}
3651
3652/// Find the designated sub-object of an rvalue.
3653template<typename SubobjectHandler>
3654typename SubobjectHandler::result_type
3655findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3656 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3657 if (Sub.Invalid)
3658 // A diagnostic will have already been produced.
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;
3666 else
3667 Info.FFDiag(E);
3668 return handler.failed();
3669 }
3670
3671 APValue *O = Obj.Value;
3672 QualType ObjType = Obj.Type;
3673 const FieldDecl *LastField = nullptr;
3674 const FieldDecl *VolatileField = nullptr;
3675
3676 // Walk the designator's path to find the subobject.
3677 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3678 // Reading an indeterminate value is undefined, but assigning over one is OK.
3679 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3680 (O->isIndeterminate() &&
3681 !isValidIndeterminateAccess(handler.AccessKind))) {
3682 if (!Info.checkingPotentialConstantExpression())
3683 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3684 << handler.AccessKind << O->isIndeterminate()
3685 << E->getSourceRange();
3686 return handler.failed();
3687 }
3688
3689 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3690 // const and volatile semantics are not applied on an object under
3691 // {con,de}struction.
3692 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3693 ObjType->isRecordType() &&
3694 Info.isEvaluatingCtorDtor(
3695 Obj.Base,
3696 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3697 ConstructionPhase::None) {
3698 ObjType = Info.Ctx.getCanonicalType(ObjType);
3699 ObjType.removeLocalConst();
3700 ObjType.removeLocalVolatile();
3701 }
3702
3703 // If this is our last pass, check that the final object type is OK.
3704 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3705 // Accesses to volatile objects are prohibited.
3706 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3707 if (Info.getLangOpts().CPlusPlus) {
3708 int DiagKind;
3709 SourceLocation Loc;
3710 const NamedDecl *Decl = nullptr;
3711 if (VolatileField) {
3712 DiagKind = 2;
3713 Loc = VolatileField->getLocation();
3714 Decl = VolatileField;
3715 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3716 DiagKind = 1;
3717 Loc = VD->getLocation();
3718 Decl = VD;
3719 } else {
3720 DiagKind = 0;
3721 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3722 Loc = E->getExprLoc();
3723 }
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;
3727 } else {
3728 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3729 }
3730 return handler.failed();
3731 }
3732
3733 // If we are reading an object of class type, there may still be more
3734 // things we need to check: if there are any mutable subobjects, we
3735 // cannot perform this read. (This only happens when performing a trivial
3736 // copy or assignment.)
3737 if (ObjType->isRecordType() &&
3738 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3739 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3740 return handler.failed();
3741 }
3742
3743 if (I == N) {
3744 if (!handler.found(*O, ObjType))
3745 return false;
3746
3747 // If we modified a bit-field, truncate it to the right width.
3748 if (isModification(handler.AccessKind) &&
3749 LastField && LastField->isBitField() &&
3750 !truncateBitfieldValue(Info, E, *O, LastField))
3751 return false;
3752
3753 return true;
3754 }
3755
3756 LastField = nullptr;
3757 if (ObjType->isArrayType()) {
3758 // Next subobject is an array element.
3759 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3760 assert(CAT && "vla in literal type?");
3761 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3762 if (CAT->getSize().ule(Index)) {
3763 // Note, it should not be possible to form a pointer with a valid
3764 // designator which points more than one past the end of the array.
3765 if (Info.getLangOpts().CPlusPlus11)
3766 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3767 << handler.AccessKind;
3768 else
3769 Info.FFDiag(E);
3770 return handler.failed();
3771 }
3772
3773 ObjType = CAT->getElementType();
3774
3775 if (O->getArrayInitializedElts() > Index)
3776 O = &O->getArrayInitializedElt(Index);
3777 else if (!isRead(handler.AccessKind)) {
3778 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3779 return handler.failed();
3780
3781 expandArray(*O, Index);
3782 O = &O->getArrayInitializedElt(Index);
3783 } else
3784 O = &O->getArrayFiller();
3785 } else if (ObjType->isAnyComplexType()) {
3786 // Next subobject is a complex number.
3787 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3788 if (Index > 1) {
3789 if (Info.getLangOpts().CPlusPlus11)
3790 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3791 << handler.AccessKind;
3792 else
3793 Info.FFDiag(E);
3794 return handler.failed();
3795 }
3796
3797 ObjType = getSubobjectType(
3798 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3799
3800 assert(I == N - 1 && "extracting subobject of scalar?");
3801 if (O->isComplexInt()) {
3802 return handler.found(Index ? O->getComplexIntImag()
3803 : O->getComplexIntReal(), ObjType);
3804 } else {
3805 assert(O->isComplexFloat());
3806 return handler.found(Index ? O->getComplexFloatImag()
3807 : O->getComplexFloatReal(), ObjType);
3808 }
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();
3816 }
3817
3818 // Next subobject is a class, struct or union field.
3819 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3820 if (RD->isUnion()) {
3821 const FieldDecl *UnionField = O->getUnionField();
3822 if (!UnionField ||
3823 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3824 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3825 // Placement new onto an inactive union member makes it active.
3826 O->setUnion(Field, APValue());
3827 } else {
3828 // FIXME: If O->getUnionValue() is absent, report that there's no
3829 // active union member rather than reporting the prior active union
3830 // member. We'll need to fix nullptr_t to not use APValue() as its
3831 // representation first.
3832 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3833 << handler.AccessKind << Field << !UnionField << UnionField;
3834 return handler.failed();
3835 }
3836 }
3837 O = &O->getUnionValue();
3838 } else
3839 O = &O->getStructField(Field->getFieldIndex());
3840
3841 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3842 LastField = Field;
3843 if (Field->getType().isVolatileQualified())
3844 VolatileField = Field;
3845 } else {
3846 // Next subobject is a base class.
3847 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3848 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3849 O = &O->getStructBase(getBaseIndex(Derived, Base));
3850
3851 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3852 }
3853 }
3854}
3855
3856namespace {
3857struct ExtractSubobjectHandler {
3858 EvalInfo &Info;
3859 const Expr *E;
3860 APValue &Result;
3861 const AccessKinds AccessKind;
3862
3863 typedef bool result_type;
3864 bool failed() { return false; }
3865 bool found(APValue &Subobj, QualType SubobjType) {
3866 Result = Subobj;
3867 if (AccessKind == AK_ReadObjectRepresentation)
3868 return true;
3869 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3870 }
3871 bool found(APSInt &Value, QualType SubobjType) {
3872 Result = APValue(Value);
3873 return true;
3874 }
3875 bool found(APFloat &Value, QualType SubobjType) {
3876 Result = APValue(Value);
3877 return true;
3878 }
3879};
3880} // end anonymous namespace
3881
3882/// Extract the designated sub-object of an rvalue.
3883static bool extractSubobject(EvalInfo &Info, const Expr *E,
3884 const CompleteObject &Obj,
3885 const SubobjectDesignator &Sub, APValue &Result,
3886 AccessKinds AK = AK_Read) {
3887 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3888 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3889 return findSubobject(Info, E, Obj, Sub, Handler);
3890}
3891
3892namespace {
3893struct ModifySubobjectHandler {
3894 EvalInfo &Info;
3895 APValue &NewVal;
3896 const Expr *E;
3897
3898 typedef bool result_type;
3899 static const AccessKinds AccessKind = AK_Assign;
3900
3901 bool checkConst(QualType QT) {
3902 // Assigning to a const object has undefined behavior.
3903 if (QT.isConstQualified()) {
3904 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3905 return false;
3906 }
3907 return true;
3908 }
3909
3910 bool failed() { return false; }
3911 bool found(APValue &Subobj, QualType SubobjType) {
3912 if (!checkConst(SubobjType))
3913 return false;
3914 // We've been given ownership of NewVal, so just swap it in.
3915 Subobj.swap(NewVal);
3916 return true;
3917 }
3918 bool found(APSInt &Value, QualType SubobjType) {
3919 if (!checkConst(SubobjType))
3920 return false;
3921 if (!NewVal.isInt()) {
3922 // Maybe trying to write a cast pointer value into a complex?
3923 Info.FFDiag(E);
3924 return false;
3925 }
3926 Value = NewVal.getInt();
3927 return true;
3928 }
3929 bool found(APFloat &Value, QualType SubobjType) {
3930 if (!checkConst(SubobjType))
3931 return false;
3932 Value = NewVal.getFloat();
3933 return true;
3934 }
3935};
3936} // end anonymous namespace
3937
3938const AccessKinds ModifySubobjectHandler::AccessKind;
3939
3940/// Update the designated sub-object of an rvalue to the given value.
3941static bool modifySubobject(EvalInfo &Info, const Expr *E,
3942 const CompleteObject &Obj,
3943 const SubobjectDesignator &Sub,
3944 APValue &NewVal) {
3945 ModifySubobjectHandler Handler = { Info, NewVal, E };
3946 return findSubobject(Info, E, Obj, Sub, Handler);
3947}
3948
3949/// Find the position where two subobject designators diverge, or equivalently
3950/// the length of the common initial subsequence.
3951static unsigned FindDesignatorMismatch(QualType ObjType,
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) {
3957 if (!ObjType.isNull() &&
3958 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3959 // Next subobject is an array element.
3960 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3961 WasArrayIndex = true;
3962 return I;
3963 }
3964 if (ObjType->isAnyComplexType())
3965 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3966 else
3967 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3968 } else {
3969 if (A.Entries[I].getAsBaseOrMember() !=
3970 B.Entries[I].getAsBaseOrMember()) {
3971 WasArrayIndex = false;
3972 return I;
3973 }
3974 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3975 // Next subobject is a field.
3976 ObjType = FD->getType();
3977 else
3978 // Next subobject is a base class.
3979 ObjType = QualType();
3980 }
3981 }
3982 WasArrayIndex = false;
3983 return I;
3984}
3985
3986/// Determine whether the given subobject designators refer to elements of the
3987/// same array object.
3989 const SubobjectDesignator &A,
3990 const SubobjectDesignator &B) {
3991 if (A.Entries.size() != B.Entries.size())
3992 return false;
3993
3994 bool IsArray = A.MostDerivedIsArrayElement;
3995 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3996 // A is a subobject of the array element.
3997 return false;
3998
3999 // If A (and B) designates an array element, the last entry will be the array
4000 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4001 // of length 1' case, and the entire path must match.
4002 bool WasArrayIndex;
4003 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4004 return CommonLength >= A.Entries.size() - IsArray;
4005}
4006
4007/// Find the complete object to which an LValue refers.
4008static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4009 AccessKinds AK, const LValue &LVal,
4010 QualType LValType) {
4011 if (LVal.InvalidBase) {
4012 Info.FFDiag(E);
4013 return CompleteObject();
4014 }
4015
4016 if (!LVal.Base) {
4017 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4018 return CompleteObject();
4019 }
4020
4021 CallStackFrame *Frame = nullptr;
4022 unsigned Depth = 0;
4023 if (LVal.getLValueCallIndex()) {
4024 std::tie(Frame, Depth) =
4025 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4026 if (!Frame) {
4027 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4028 << AK << LVal.Base.is<const ValueDecl*>();
4029 NoteLValueLocation(Info, LVal.Base);
4030 return CompleteObject();
4031 }
4032 }
4033
4034 bool IsAccess = isAnyAccess(AK);
4035
4036 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4037 // is not a constant expression (even if the object is non-volatile). We also
4038 // apply this rule to C++98, in order to conform to the expected 'volatile'
4039 // semantics.
4040 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4041 if (Info.getLangOpts().CPlusPlus)
4042 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4043 << AK << LValType;
4044 else
4045 Info.FFDiag(E);
4046 return CompleteObject();
4047 }
4048
4049 // Compute value storage location and type of base object.
4050 APValue *BaseVal = nullptr;
4051 QualType BaseType = getType(LVal.Base);
4052
4053 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4054 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4055 // This is the object whose initializer we're evaluating, so its lifetime
4056 // started in the current evaluation.
4057 BaseVal = Info.EvaluatingDeclValue;
4058 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4059 // Allow reading from a GUID declaration.
4060 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4061 if (isModification(AK)) {
4062 // All the remaining cases do not permit modification of the object.
4063 Info.FFDiag(E, diag::note_constexpr_modify_global);
4064 return CompleteObject();
4065 }
4066 APValue &V = GD->getAsAPValue();
4067 if (V.isAbsent()) {
4068 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4069 << GD->getType();
4070 return CompleteObject();
4071 }
4072 return CompleteObject(LVal.Base, &V, GD->getType());
4073 }
4074
4075 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4076 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4077 if (isModification(AK)) {
4078 Info.FFDiag(E, diag::note_constexpr_modify_global);
4079 return CompleteObject();
4080 }
4081 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4082 GCD->getType());
4083 }
4084
4085 // Allow reading from template parameter objects.
4086 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4087 if (isModification(AK)) {
4088 Info.FFDiag(E, diag::note_constexpr_modify_global);
4089 return CompleteObject();
4090 }
4091 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4092 TPO->getType());
4093 }
4094
4095 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4096 // In C++11, constexpr, non-volatile variables initialized with constant
4097 // expressions are constant expressions too. Inside constexpr functions,
4098 // parameters are constant expressions even if they're non-const.
4099 // In C++1y, objects local to a constant expression (those with a Frame) are
4100 // both readable and writable inside constant expressions.
4101 // In C, such things can also be folded, although they are not ICEs.
4102 const VarDecl *VD = dyn_cast<VarDecl>(D);
4103 if (VD) {
4104 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4105 VD = VDef;
4106 }
4107 if (!VD || VD->isInvalidDecl()) {
4108 Info.FFDiag(E);
4109 return CompleteObject();
4110 }
4111
4112 bool IsConstant = BaseType.isConstant(Info.Ctx);
4113
4114 // Unless we're looking at a local variable or argument in a constexpr call,
4115 // the variable we're reading must be const.
4116 if (!Frame) {
4117 if (IsAccess && isa<ParmVarDecl>(VD)) {
4118 // Access of a parameter that's not associated with a frame isn't going
4119 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4120 // suitable diagnostic.
4121 } else if (Info.getLangOpts().CPlusPlus14 &&
4122 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4123 // OK, we can read and modify an object if we're in the process of
4124 // evaluating its initializer, because its lifetime began in this
4125 // evaluation.
4126 } else if (isModification(AK)) {
4127 // All the remaining cases do not permit modification of the object.
4128 Info.FFDiag(E, diag::note_constexpr_modify_global);
4129 return CompleteObject();
4130 } else if (VD->isConstexpr()) {
4131 // OK, we can read this variable.
4132 } else if (BaseType->isIntegralOrEnumerationType()) {
4133 if (!IsConstant) {
4134 if (!IsAccess)
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);
4139 } else {
4140 Info.FFDiag(E);
4141 }
4142 return CompleteObject();
4143 }
4144 } else if (!IsAccess) {
4145 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4146 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4147 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4148 // This variable might end up being constexpr. Don't diagnose it yet.
4149 } else if (IsConstant) {
4150 // Keep evaluating to see what we can do. In particular, we support
4151 // folding of const floating-point types, in order to make static const
4152 // data members of such types (supported as an extension) more useful.
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)
4157 << VD << BaseType;
4158 Info.Note(VD->getLocation(), diag::note_declared_at);
4159 } else {
4160 Info.CCEDiag(E);
4161 }
4162 } else {
4163 // Never allow reading a non-const value.
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)
4168 << VD << BaseType;
4169 Info.Note(VD->getLocation(), diag::note_declared_at);
4170 } else {
4171 Info.FFDiag(E);
4172 }
4173 return CompleteObject();
4174 }
4175 }
4176
4177 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4178 return CompleteObject();
4179 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4180 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4181 if (!Alloc) {
4182 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4183 return CompleteObject();
4184 }
4185 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4186 LVal.Base.getDynamicAllocType());
4187 } else {
4188 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4189
4190 if (!Frame) {
4191 if (const MaterializeTemporaryExpr *MTE =
4192 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4193 assert(MTE->getStorageDuration() == SD_Static &&
4194 "should have a frame for a non-global materialized temporary");
4195
4196 // C++20 [expr.const]p4: [DR2126]
4197 // An object or reference is usable in constant expressions if it is
4198 // - a temporary object of non-volatile const-qualified literal type
4199 // whose lifetime is extended to that of a variable that is usable
4200 // in constant expressions
4201 //
4202 // C++20 [expr.const]p5:
4203 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4204 // - a non-volatile glvalue that refers to an object that is usable
4205 // in constant expressions, or
4206 // - a non-volatile glvalue of literal type that refers to a
4207 // non-volatile object whose lifetime began within the evaluation
4208 // of E;
4209 //
4210 // C++11 misses the 'began within the evaluation of e' check and
4211 // instead allows all temporaries, including things like:
4212 // int &&r = 1;
4213 // int x = ++r;
4214 // constexpr int k = r;
4215 // Therefore we use the C++14-onwards rules in C++11 too.
4216 //
4217 // Note that temporaries whose lifetimes began while evaluating a
4218 // variable's constructor are not usable while evaluating the
4219 // corresponding destructor, not even if they're of const-qualified
4220 // types.
4221 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4222 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4223 if (!IsAccess)
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();
4228 }
4229
4230 BaseVal = MTE->getOrCreateValue(false);
4231 assert(BaseVal && "got reference to unevaluated temporary");
4232 } else {
4233 if (!IsAccess)
4234 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4235 APValue Val;
4236 LVal.moveInto(Val);
4237 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4238 << AK
4239 << Val.getAsString(Info.Ctx,
4240 Info.Ctx.getLValueReferenceType(LValType));
4241 NoteLValueLocation(Info, LVal.Base);
4242 return CompleteObject();
4243 }
4244 } else {
4245 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4246 assert(BaseVal && "missing value for temporary");
4247 }
4248 }
4249
4250 // In C++14, we can't safely access any mutable state when we might be
4251 // evaluating after an unmodeled side effect. Parameters are modeled as state
4252 // in the caller, but aren't visible once the call returns, so they can be
4253 // modified in a speculatively-evaluated call.
4254 //
4255 // FIXME: Not all local state is mutable. Allow local constant subobjects
4256 // to be read here (but take care with 'mutable' fields).
4257 unsigned VisibleDepth = Depth;
4258 if (llvm::isa_and_nonnull<ParmVarDecl>(
4259 LVal.Base.dyn_cast<const ValueDecl *>()))
4260 ++VisibleDepth;
4261 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4262 Info.EvalStatus.HasSideEffects) ||
4263 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4264 return CompleteObject();
4265
4266 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4267}
4268
4269/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4270/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4271/// glvalue referred to by an entity of reference type.
4272///
4273/// \param Info - Information about the ongoing evaluation.
4274/// \param Conv - The expression for which we are performing the conversion.
4275/// Used for diagnostics.
4276/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4277/// case of a non-class type).
4278/// \param LVal - The glvalue on which we are attempting to perform this action.
4279/// \param RVal - The produced value will be placed here.
4280/// \param WantObjectRepresentation - If true, we're looking for the object
4281/// representation rather than the value, and in particular,
4282/// there is no requirement that the result be fully initialized.
4283static bool
4285 const LValue &LVal, APValue &RVal,
4286 bool WantObjectRepresentation = false) {
4287 if (LVal.Designator.Invalid)
4288 return false;
4289
4290 // Check for special cases where there is no existing APValue to look at.
4291 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4292
4293 AccessKinds AK =
4294 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4295
4296 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4297 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4298 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4299 // initializer until now for such expressions. Such an expression can't be
4300 // an ICE in C, so this only matters for fold.
4301 if (Type.isVolatileQualified()) {
4302 Info.FFDiag(Conv);
4303 return false;
4304 }
4305
4306 APValue Lit;
4307 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4308 return false;
4309
4310 // According to GCC info page:
4311 //
4312 // 6.28 Compound Literals
4313 //
4314 // As an optimization, G++ sometimes gives array compound literals longer
4315 // lifetimes: when the array either appears outside a function or has a
4316 // const-qualified type. If foo and its initializer had elements of type
4317 // char *const rather than char *, or if foo were a global variable, the
4318 // array would have static storage duration. But it is probably safest
4319 // just to avoid the use of array compound literals in C++ code.
4320 //
4321 // Obey that rule by checking constness for converted array types.
4322
4323 QualType CLETy = CLE->getType();
4324 if (CLETy->isArrayType() && !Type->isArrayType()) {
4325 if (!CLETy.isConstant(Info.Ctx)) {
4326 Info.FFDiag(Conv);
4327 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4328 return false;
4329 }
4330 }
4331
4332 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4333 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4334 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4335 // Special-case character extraction so we don't have to construct an
4336 // APValue for the whole string.
4337 assert(LVal.Designator.Entries.size() <= 1 &&
4338 "Can only read characters from string literals");
4339 if (LVal.Designator.Entries.empty()) {
4340 // Fail for now for LValue to RValue conversion of an array.
4341 // (This shouldn't show up in C/C++, but it could be triggered by a
4342 // weird EvaluateAsRValue call from a tool.)
4343 Info.FFDiag(Conv);
4344 return false;
4345 }
4346 if (LVal.Designator.isOnePastTheEnd()) {
4347 if (Info.getLangOpts().CPlusPlus11)
4348 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4349 else
4350 Info.FFDiag(Conv);
4351 return false;
4352 }
4353 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4354 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4355 return true;
4356 }
4357 }
4358
4359 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4360 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4361}
4362
4363/// Perform an assignment of Val to LVal. Takes ownership of Val.
4364static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4365 QualType LValType, APValue &Val) {
4366 if (LVal.Designator.Invalid)
4367 return false;
4368
4369 if (!Info.getLangOpts().CPlusPlus14) {
4370 Info.FFDiag(E);
4371 return false;
4372 }
4373
4374 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4375 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4376}
4377
4378namespace {
4379struct CompoundAssignSubobjectHandler {
4380 EvalInfo &Info;
4381 const CompoundAssignOperator *E;
4382 QualType PromotedLHSType;
4384 const APValue &RHS;
4385
4386 static const AccessKinds AccessKind = AK_Assign;
4387
4388 typedef bool result_type;
4389
4390 bool checkConst(QualType QT) {
4391 // Assigning to a const object has undefined behavior.
4392 if (QT.isConstQualified()) {
4393 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4394 return false;
4395 }
4396 return true;
4397 }
4398
4399 bool failed() { return false; }
4400 bool found(APValue &Subobj, QualType SubobjType) {
4401 switch (Subobj.getKind()) {
4402 case APValue::Int:
4403 return found(Subobj.getInt(), SubobjType);
4404 case APValue::Float:
4405 return found(Subobj.getFloat(), SubobjType);
4408 // FIXME: Implement complex compound assignment.
4409 Info.FFDiag(E);
4410 return false;
4411 case APValue::LValue:
4412 return foundPointer(Subobj, SubobjType);
4413 case APValue::Vector:
4414 return foundVector(Subobj, SubobjType);
4416 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4417 << /*read of=*/0 << /*uninitialized object=*/1
4418 << E->getLHS()->getSourceRange();
4419 return false;
4420 default:
4421 // FIXME: can this happen?
4422 Info.FFDiag(E);
4423 return false;
4424 }
4425 }
4426
4427 bool foundVector(APValue &Value, QualType SubobjType) {
4428 if (!checkConst(SubobjType))
4429 return false;
4430
4431 if (!SubobjType->isVectorType()) {
4432 Info.FFDiag(E);
4433 return false;
4434 }
4435 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4436 }
4437
4438 bool found(APSInt &Value, QualType SubobjType) {
4439 if (!checkConst(SubobjType))
4440 return false;
4441
4442 if (!SubobjType->isIntegerType()) {
4443 // We don't support compound assignment on integer-cast-to-pointer
4444 // values.
4445 Info.FFDiag(E);
4446 return false;
4447 }
4448
4449 if (RHS.isInt()) {
4450 APSInt LHS =
4451 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4452 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4453 return false;
4454 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4455 return true;
4456 } else if (RHS.isFloat()) {
4457 const FPOptions FPO = E->getFPFeaturesInEffect(
4458 Info.Ctx.getLangOpts());
4459 APFloat FValue(0.0);
4460 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4461 PromotedLHSType, FValue) &&
4462 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4463 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4464 Value);
4465 }
4466
4467 Info.FFDiag(E);
4468 return false;
4469 }
4470 bool found(APFloat &Value, QualType SubobjType) {
4471 return checkConst(SubobjType) &&
4472 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4473 Value) &&
4474 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4475 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4476 }
4477 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4478 if (!checkConst(SubobjType))
4479 return false;
4480
4481 QualType PointeeType;
4482 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4483 PointeeType = PT->getPointeeType();
4484
4485 if (PointeeType.isNull() || !RHS.isInt() ||
4486 (Opcode != BO_Add && Opcode != BO_Sub)) {
4487 Info.FFDiag(E);
4488 return false;
4489 }
4490
4491 APSInt Offset = RHS.getInt();
4492 if (Opcode == BO_Sub)
4493 negateAsSigned(Offset);
4494
4495 LValue LVal;
4496 LVal.setFrom(Info.Ctx, Subobj);
4497 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4498 return false;
4499 LVal.moveInto(Subobj);
4500 return true;
4501 }
4502};
4503} // end anonymous namespace
4504
4505const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4506
4507/// Perform a compound assignment of LVal <op>= RVal.
4508static bool handleCompoundAssignment(EvalInfo &Info,
4509 const CompoundAssignOperator *E,
4510 const LValue &LVal, QualType LValType,
4511 QualType PromotedLValType,
4512 BinaryOperatorKind Opcode,
4513 const APValue &RVal) {
4514 if (LVal.Designator.Invalid)
4515 return false;
4516
4517 if (!Info.getLangOpts().CPlusPlus14) {
4518 Info.FFDiag(E);
4519 return false;
4520 }
4521
4522 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4523 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4524 RVal };
4525 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4526}
4527
4528namespace {
4529struct IncDecSubobjectHandler {
4530 EvalInfo &Info;
4531 const UnaryOperator *E;
4532 AccessKinds AccessKind;
4533 APValue *Old;
4534
4535 typedef bool result_type;
4536
4537 bool checkConst(QualType QT) {
4538 // Assigning to a const object has undefined behavior.
4539 if (QT.isConstQualified()) {
4540 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4541 return false;
4542 }
4543 return true;
4544 }
4545
4546 bool failed() { return false; }
4547 bool found(APValue &Subobj, QualType SubobjType) {
4548 // Stash the old value. Also clear Old, so we don't clobber it later
4549 // if we're post-incrementing a complex.
4550 if (Old) {
4551 *Old = Subobj;
4552 Old = nullptr;
4553 }
4554
4555 switch (Subobj.getKind()) {
4556 case APValue::Int:
4557 return found(Subobj.getInt(), SubobjType);
4558 case APValue::Float:
4559 return found(Subobj.getFloat(), SubobjType);
4561 return found(Subobj.getComplexIntReal(),
4562 SubobjType->castAs<ComplexType>()->getElementType()
4563 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4565 return found(Subobj.getComplexFloatReal(),
4566 SubobjType->castAs<ComplexType>()->getElementType()
4567 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4568 case APValue::LValue:
4569 return foundPointer(Subobj, SubobjType);
4570 default:
4571 // FIXME: can this happen?
4572 Info.FFDiag(E);
4573 return false;
4574 }
4575 }
4576 bool found(APSInt &Value, QualType SubobjType) {
4577 if (!checkConst(SubobjType))
4578 return false;
4579
4580 if (!SubobjType->isIntegerType()) {
4581 // We don't support increment / decrement on integer-cast-to-pointer
4582 // values.
4583 Info.FFDiag(E);
4584 return false;
4585 }
4586
4587 if (Old) *Old = APValue(Value);
4588
4589 // bool arithmetic promotes to int, and the conversion back to bool
4590 // doesn't reduce mod 2^n, so special-case it.
4591 if (SubobjType->isBooleanType()) {
4592 if (AccessKind == AK_Increment)
4593 Value = 1;
4594 else
4595 Value = !Value;
4596 return true;
4597 }
4598
4599 bool WasNegative = Value.isNegative();
4600 if (AccessKind == AK_Increment) {
4601 ++Value;
4602
4603 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4604 APSInt ActualValue(Value, /*IsUnsigned*/true);
4605 return HandleOverflow(Info, E, ActualValue, SubobjType);
4606 }
4607 } else {
4608 --Value;
4609
4610 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4611 unsigned BitWidth = Value.getBitWidth();
4612 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4613 ActualValue.setBit(BitWidth);
4614 return HandleOverflow(Info, E, ActualValue, SubobjType);
4615 }
4616 }
4617 return true;
4618 }
4619 bool found(APFloat &Value, QualType SubobjType) {
4620 if (!checkConst(SubobjType))
4621 return false;
4622
4623 if (Old) *Old = APValue(Value);
4624
4625 APFloat One(Value.getSemantics(), 1);
4626 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4627 APFloat::opStatus St;
4628 if (AccessKind == AK_Increment)
4629 St = Value.add(One, RM);
4630 else
4631 St = Value.subtract(One, RM);
4632 return checkFloatingPointResult(Info, E, St);
4633 }
4634 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4635 if (!checkConst(SubobjType))
4636 return false;
4637
4638 QualType PointeeType;
4639 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4640 PointeeType = PT->getPointeeType();
4641 else {
4642 Info.FFDiag(E);
4643 return false;
4644 }
4645
4646 LValue LVal;
4647 LVal.setFrom(Info.Ctx, Subobj);
4648 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4649 AccessKind == AK_Increment ? 1 : -1))
4650 return false;
4651 LVal.moveInto(Subobj);
4652 return true;
4653 }
4654};
4655} // end anonymous namespace
4656
4657/// Perform an increment or decrement on LVal.
4658static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4659 QualType LValType, bool IsIncrement, APValue *Old) {
4660 if (LVal.Designator.Invalid)
4661 return false;
4662
4663 if (!Info.getLangOpts().CPlusPlus14) {
4664 Info.FFDiag(E);
4665 return false;
4666 }
4667
4668 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4669 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4670 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4671 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4672}
4673
4674/// Build an lvalue for the object argument of a member function call.
4675static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4676 LValue &This) {
4677 if (Object->getType()->isPointerType() && Object->isPRValue())
4678 return EvaluatePointer(Object, This, Info);
4679
4680 if (Object->isGLValue())
4681 return EvaluateLValue(Object, This, Info);
4682
4683 if (Object->getType()->isLiteralType(Info.Ctx))
4684 return EvaluateTemporary(Object, This, Info);
4685
4686 if (Object->getType()->isRecordType() && Object->isPRValue())
4687 return EvaluateTemporary(Object, This, Info);
4688
4689 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4690 return false;
4691}
4692
4693/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4694/// lvalue referring to the result.
4695///
4696/// \param Info - Information about the ongoing evaluation.
4697/// \param LV - An lvalue referring to the base of the member pointer.
4698/// \param RHS - The member pointer expression.
4699/// \param IncludeMember - Specifies whether the member itself is included in
4700/// the resulting LValue subobject designator. This is not possible when
4701/// creating a bound member function.
4702/// \return The field or method declaration to which the member pointer refers,
4703/// or 0 if evaluation fails.
4704static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4705 QualType LVType,
4706 LValue &LV,
4707 const Expr *RHS,
4708 bool IncludeMember = true) {
4709 MemberPtr MemPtr;
4710 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4711 return nullptr;
4712
4713 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4714 // member value, the behavior is undefined.
4715 if (!MemPtr.getDecl()) {
4716 // FIXME: Specific diagnostic.
4717 Info.FFDiag(RHS);
4718 return nullptr;
4719 }
4720
4721 if (MemPtr.isDerivedMember()) {
4722 // This is a member of some derived class. Truncate LV appropriately.
4723 // The end of the derived-to-base path for the base object must match the
4724 // derived-to-base path for the member pointer.
4725 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4726 LV.Designator.Entries.size()) {
4727 Info.FFDiag(RHS);
4728 return nullptr;
4729 }
4730 unsigned PathLengthToMember =
4731 LV.Designator.Entries.size() - MemPtr.Path.size();
4732 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4733 const CXXRecordDecl *LVDecl = getAsBaseClass(
4734 LV.Designator.Entries[PathLengthToMember + I]);
4735 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4736 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4737 Info.FFDiag(RHS);
4738 return nullptr;
4739 }
4740 }
4741
4742 // Truncate the lvalue to the appropriate derived class.
4743 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4744 PathLengthToMember))
4745 return nullptr;
4746 } else if (!MemPtr.Path.empty()) {
4747 // Extend the LValue path with the member pointer's path.
4748 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4749 MemPtr.Path.size() + IncludeMember);
4750
4751 // Walk down to the appropriate base class.
4752 if (const PointerType *PT = LVType->getAs<PointerType>())
4753 LVType = PT->getPointeeType();
4754 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4755 assert(RD && "member pointer access on non-class-type expression");
4756 // The first class in the path is that of the lvalue.
4757 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4758 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4759 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4760 return nullptr;
4761 RD = Base;
4762 }
4763 // Finally cast to the class containing the member.
4764 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4765 MemPtr.getContainingRecord()))
4766 return nullptr;
4767 }
4768
4769 // Add the member. Note that we cannot build bound member functions here.
4770 if (IncludeMember) {
4771 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4772 if (!HandleLValueMember(Info, RHS, LV, FD))
4773 return nullptr;
4774 } else if (const IndirectFieldDecl *IFD =
4775 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4776 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4777 return nullptr;
4778 } else {
4779 llvm_unreachable("can't construct reference to bound member function");
4780 }
4781 }
4782
4783 return MemPtr.getDecl();
4784}
4785
4786static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4787 const BinaryOperator *BO,
4788 LValue &LV,
4789 bool IncludeMember = true) {
4790 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4791
4792 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4793 if (Info.noteFailure()) {
4794 MemberPtr MemPtr;
4795 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4796 }
4797 return nullptr;
4798 }
4799
4800 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4801 BO->getRHS(), IncludeMember);
4802}
4803
4804/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4805/// the provided lvalue, which currently refers to the base object.
4806static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4807 LValue &Result) {
4808 SubobjectDesignator &D = Result.Designator;
4809 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4810 return false;
4811
4812 QualType TargetQT = E->getType();
4813 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4814 TargetQT = PT->getPointeeType();
4815
4816 // Check this cast lands within the final derived-to-base subobject path.
4817 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4818 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4819 << D.MostDerivedType << TargetQT;
4820 return false;
4821 }
4822
4823 // Check the type of the final cast. We don't need to check the path,
4824 // since a cast can only be formed if the path is unique.
4825 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4826 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4827 const CXXRecordDecl *FinalType;
4828 if (NewEntriesSize == D.MostDerivedPathLength)
4829 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4830 else
4831 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4832 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4833 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4834 << D.MostDerivedType << TargetQT;
4835 return false;
4836 }
4837
4838 // Truncate the lvalue to the appropriate derived class.
4839 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4840}
4841
4842/// Get the value to use for a default-initialized object of type T.
4843/// Return false if it encounters something invalid.
4844static bool handleDefaultInitValue(QualType T, APValue &Result) {
4845 bool Success = true;
4846
4847 // If there is already a value present don't overwrite it.
4848 if (!Result.isAbsent())
4849 return true;
4850
4851 if (auto *RD = T->getAsCXXRecordDecl()) {
4852 if (RD->isInvalidDecl()) {
4853 Result = APValue();
4854 return false;
4855 }
4856 if (RD->isUnion()) {
4857 Result = APValue((const FieldDecl *)nullptr);
4858 return true;
4859 }
4860 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4861 std::distance(RD->field_begin(), RD->field_end()));
4862
4863 unsigned Index = 0;
4864 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4865 End = RD->bases_end();
4866 I != End; ++I, ++Index)
4867 Success &=
4868 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4869
4870 for (const auto *I : RD->fields()) {
4871 if (I->isUnnamedBitfield())
4872 continue;
4873 Success &= handleDefaultInitValue(
4874 I->getType(), Result.getStructField(I->getFieldIndex()));
4875 }
4876 return Success;
4877 }
4878
4879 if (auto *AT =
4880 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4881 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4882 if (Result.hasArrayFiller())
4883 Success &=
4884 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4885
4886 return Success;
4887 }
4888
4889 Result = APValue::IndeterminateValue();
4890 return true;
4891}
4892
4893namespace {
4894enum EvalStmtResult {
4895 /// Evaluation failed.
4896 ESR_Failed,
4897 /// Hit a 'return' statement.
4898 ESR_Returned,
4899 /// Evaluation succeeded.
4900 ESR_Succeeded,
4901 /// Hit a 'continue' statement.
4902 ESR_Continue,
4903 /// Hit a 'break' statement.
4904 ESR_Break,
4905 /// Still scanning for 'case' or 'default' statement.
4906 ESR_CaseNotFound
4907};
4908}
4909
4910static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4911 if (VD->isInvalidDecl())
4912 return false;
4913 // We don't need to evaluate the initializer for a static local.
4914 if (!VD->hasLocalStorage())
4915 return true;
4916
4917 LValue Result;
4918 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4919 ScopeKind::Block, Result);
4920
4921 const Expr *InitE = VD->getInit();
4922 if (!InitE) {
4923 if (VD->getType()->isDependentType())
4924 return Info.noteSideEffect();
4925 return handleDefaultInitValue(VD->getType(), Val);
4926 }
4927 if (InitE->isValueDependent())
4928 return false;
4929
4930 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4931 // Wipe out any partially-computed value, to allow tracking that this
4932 // evaluation failed.
4933 Val = APValue();
4934 return false;
4935 }
4936
4937 return true;
4938}
4939
4940static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4941 bool OK = true;
4942
4943 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4944 OK &= EvaluateVarDecl(Info, VD);
4945
4946 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4947 for (auto *BD : DD->bindings())
4948 if (auto *VD = BD->getHoldingVar())
4949 OK &= EvaluateDecl(Info, VD);
4950
4951 return OK;
4952}
4953
4954static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4955 assert(E->isValueDependent());
4956 if (Info.noteSideEffect())
4957 return true;
4958 assert(E->containsErrors() && "valid value-dependent expression should never "
4959 "reach invalid code path.");
4960 return false;
4961}
4962
4963/// Evaluate a condition (either a variable declaration or an expression).
4964static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4965 const Expr *Cond, bool &Result) {
4966 if (Cond->isValueDependent())
4967 return false;
4968 FullExpressionRAII Scope(Info);
4969 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4970 return false;
4971 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4972 return false;
4973 return Scope.destroy();
4974}
4975
4976namespace {
4977/// A location where the result (returned value) of evaluating a
4978/// statement should be stored.
4979struct StmtResult {
4980 /// The APValue that should be filled in with the returned value.
4981 APValue &Value;
4982 /// The location containing the result, if any (used to support RVO).
4983 const LValue *Slot;
4984};
4985
4986struct TempVersionRAII {
4987 CallStackFrame &Frame;
4988
4989 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4990 Frame.pushTempVersion();
4991 }
4992
4993 ~TempVersionRAII() {
4994 Frame.popTempVersion();
4995 }
4996};
4997
4998}
4999
5000static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5001 const Stmt *S,
5002 const SwitchCase *SC = nullptr);
5003
5004/// Evaluate the body of a loop, and translate the result as appropriate.
5005static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5006 const Stmt *Body,
5007 const SwitchCase *Case = nullptr) {
5008 BlockScopeRAII Scope(Info);
5009
5010 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5011 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5012 ESR = ESR_Failed;
5013
5014 switch (ESR) {
5015 case ESR_Break:
5016 return ESR_Succeeded;
5017 case ESR_Succeeded:
5018 case ESR_Continue:
5019 return ESR_Continue;
5020 case ESR_Failed:
5021 case ESR_Returned:
5022 case ESR_CaseNotFound:
5023 return ESR;
5024 }
5025 llvm_unreachable("Invalid EvalStmtResult!");
5026}
5027
5028/// Evaluate a switch statement.
5029static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5030 const SwitchStmt *SS) {
5031 BlockScopeRAII Scope(Info);
5032
5033 // Evaluate the switch condition.
5034 APSInt Value;
5035 {
5036 if (const Stmt *Init = SS->getInit()) {
5037 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5038 if (ESR != ESR_Succeeded) {
5039 if (ESR != ESR_Failed && !Scope.destroy())
5040 ESR = ESR_Failed;
5041 return ESR;
5042 }
5043 }
5044
5045 FullExpressionRAII CondScope(Info);
5046 if (SS->getConditionVariable() &&
5047 !EvaluateDecl(Info, SS->getConditionVariable()))
5048 return ESR_Failed;
5049 if (SS->getCond()->isValueDependent()) {
5050 // We don't know what the value is, and which branch should jump to.
5051 EvaluateDependentExpr(SS->getCond(), Info);
5052 return ESR_Failed;
5053 }
5054 if (!EvaluateInteger(SS->getCond(), Value, Info))
5055 return ESR_Failed;
5056
5057 if (!CondScope.destroy())
5058 return ESR_Failed;
5059 }
5060
5061 // Find the switch case corresponding to the value of the condition.
5062 // FIXME: Cache this lookup.
5063 const SwitchCase *Found = nullptr;
5064 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5065 SC = SC->getNextSwitchCase()) {
5066 if (isa<DefaultStmt>(SC)) {
5067 Found = SC;
5068 continue;
5069 }
5070
5071 const CaseStmt *CS = cast<CaseStmt>(SC);
5072 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5073 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5074 : LHS;
5075 if (LHS <= Value && Value <= RHS) {
5076 Found = SC;
5077 break;
5078 }
5079 }
5080
5081 if (!Found)
5082 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5083
5084 // Search the switch body for the switch case and evaluate it from there.
5085 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5086 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5087 return ESR_Failed;
5088
5089 switch (ESR) {
5090 case ESR_Break:
5091 return ESR_Succeeded;
5092 case ESR_Succeeded:
5093 case ESR_Continue:
5094 case ESR_Failed:
5095 case ESR_Returned:
5096 return ESR;
5097 case ESR_CaseNotFound:
5098 // This can only happen if the switch case is nested within a statement
5099 // expression. We have no intention of supporting that.
5100 Info.FFDiag(Found->getBeginLoc(),
5101 diag::note_constexpr_stmt_expr_unsupported);
5102 return ESR_Failed;
5103 }
5104 llvm_unreachable("Invalid EvalStmtResult!");
5105}
5106
5107static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5108 // An expression E is a core constant expression unless the evaluation of E
5109 // would evaluate one of the following: [C++23] - a control flow that passes
5110 // through a declaration of a variable with static or thread storage duration
5111 // unless that variable is usable in constant expressions.
5112 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5113 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5114 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5115 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5116 return false;
5117 }
5118 return true;
5119}
5120
5121// Evaluate a statement.
5122static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5123 const Stmt *S, const SwitchCase *Case) {
5124 if (!Info.nextStep(S))
5125 return ESR_Failed;
5126
5127 // If we're hunting down a 'case' or 'default' label, recurse through
5128 // substatements until we hit the label.
5129 if (Case) {
5130 switch (S->getStmtClass()) {
5131 case Stmt::CompoundStmtClass:
5132 // FIXME: Precompute which substatement of a compound statement we
5133 // would jump to, and go straight there rather than performing a
5134 // linear scan each time.
5135 case Stmt::LabelStmtClass:
5136 case Stmt::AttributedStmtClass:
5137 case Stmt::DoStmtClass:
5138 break;
5139
5140 case Stmt::CaseStmtClass:
5141 case Stmt::DefaultStmtClass:
5142 if (Case == S)
5143 Case = nullptr;
5144 break;
5145
5146 case Stmt::IfStmtClass: {
5147 // FIXME: Precompute which side of an 'if' we would jump to, and go
5148 // straight there rather than scanning both sides.
5149 const IfStmt *IS = cast<IfStmt>(S);
5150
5151 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5152 // preceded by our switch label.
5153 BlockScopeRAII Scope(Info);
5154
5155 // Step into the init statement in case it brings an (uninitialized)
5156 // variable into scope.
5157 if (const Stmt *Init = IS->getInit()) {
5158 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5159 if (ESR != ESR_CaseNotFound) {
5160 assert(ESR != ESR_Succeeded);
5161 return ESR;
5162 }
5163 }
5164
5165 // Condition variable must be initialized if it exists.
5166 // FIXME: We can skip evaluating the body if there's a condition
5167 // variable, as there can't be any case labels within it.
5168 // (The same is true for 'for' statements.)
5169
5170 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5171 if (ESR == ESR_Failed)
5172 return ESR;
5173 if (ESR != ESR_CaseNotFound)
5174 return Scope.destroy() ? ESR : ESR_Failed;
5175 if (!IS->getElse())
5176 return ESR_CaseNotFound;
5177
5178 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5179 if (ESR == ESR_Failed)
5180 return ESR;
5181 if (ESR != ESR_CaseNotFound)
5182 return Scope.destroy() ? ESR : ESR_Failed;
5183 return ESR_CaseNotFound;
5184 }
5185
5186 case Stmt::WhileStmtClass: {
5187 EvalStmtResult ESR =
5188 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5189 if (ESR != ESR_Continue)
5190 return ESR;
5191 break;
5192 }
5193
5194 case Stmt::ForStmtClass: {
5195 const ForStmt *FS = cast<ForStmt>(S);
5196 BlockScopeRAII Scope(Info);
5197
5198 // Step into the init statement in case it brings an (uninitialized)
5199 // variable into scope.
5200 if (const Stmt *Init = FS->getInit()) {
5201 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5202 if (ESR != ESR_CaseNotFound) {
5203 assert(ESR != ESR_Succeeded);
5204 return ESR;
5205 }
5206 }
5207
5208 EvalStmtResult ESR =
5209 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5210 if (ESR != ESR_Continue)
5211 return ESR;
5212 if (const auto *Inc = FS->getInc()) {
5213 if (Inc->isValueDependent()) {
5214 if (!EvaluateDependentExpr(Inc, Info))
5215 return ESR_Failed;
5216 } else {
5217 FullExpressionRAII IncScope(Info);
5218 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5219 return ESR_Failed;
5220 }
5221 }
5222 break;
5223 }
5224
5225 case Stmt::DeclStmtClass: {
5226 // Start the lifetime of any uninitialized variables we encounter. They
5227 // might be used by the selected branch of the switch.
5228 const DeclStmt *DS = cast<DeclStmt>(S);
5229 for (const auto *D : DS->decls()) {
5230 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5231 if (!CheckLocalVariableDeclaration(Info, VD))
5232 return ESR_Failed;
5233 if (VD->hasLocalStorage() && !VD->getInit())
5234 if (!EvaluateVarDecl(Info, VD))
5235 return ESR_Failed;
5236 // FIXME: If the variable has initialization that can't be jumped
5237 // over, bail out of any immediately-surrounding compound-statement
5238 // too. There can't be any case labels here.
5239 }
5240 }
5241 return ESR_CaseNotFound;
5242 }
5243
5244 default:
5245 return ESR_CaseNotFound;
5246 }
5247 }
5248
5249 switch (S->getStmtClass()) {
5250 default:
5251 if (const Expr *E = dyn_cast<Expr>(S)) {
5252 if (E->isValueDependent()) {
5253 if (!EvaluateDependentExpr(E, Info))
5254 return ESR_Failed;
5255 } else {
5256 // Don't bother evaluating beyond an expression-statement which couldn't
5257 // be evaluated.
5258 // FIXME: Do we need the FullExpressionRAII object here?
5259 // VisitExprWithCleanups should create one when necessary.
5260 FullExpressionRAII Scope(Info);
5261 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5262 return ESR_Failed;
5263 }
5264 return ESR_Succeeded;
5265 }
5266
5267 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5268 return ESR_Failed;
5269
5270 case Stmt::NullStmtClass:
5271 return ESR_Succeeded;
5272
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);
5277 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5278 return ESR_Failed;
5279 // Each declaration initialization is its own full-expression.
5280 FullExpressionRAII Scope(Info);
5281 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5282 return ESR_Failed;
5283 if (!Scope.destroy())
5284 return ESR_Failed;
5285 }
5286 return ESR_Succeeded;
5287 }
5288
5289 case Stmt::ReturnStmtClass: {
5290 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5291 FullExpressionRAII Scope(Info);
5292 if (RetExpr && RetExpr->isValueDependent()) {
5293 EvaluateDependentExpr(RetExpr, Info);
5294 // We know we returned, but we don't know what the value is.
5295 return ESR_Failed;
5296 }
5297 if (RetExpr &&
5298 !(Result.Slot
5299 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5300 : Evaluate(Result.Value, Info, RetExpr)))
5301 return ESR_Failed;
5302 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5303 }
5304
5305 case Stmt::CompoundStmtClass: {
5306 BlockScopeRAII Scope(Info);
5307
5308 const CompoundStmt *CS = cast<CompoundStmt>(S);
5309 for (const auto *BI : CS->body()) {
5310 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5311 if (ESR == ESR_Succeeded)
5312 Case = nullptr;
5313 else if (ESR != ESR_CaseNotFound) {
5314 if (ESR != ESR_Failed && !Scope.destroy())
5315 return ESR_Failed;
5316 return ESR;
5317 }
5318 }
5319 if (Case)
5320 return ESR_CaseNotFound;
5321 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5322 }
5323
5324 case Stmt::IfStmtClass: {
5325 const IfStmt *IS = cast<IfStmt>(S);
5326
5327 // Evaluate the condition, as either a var decl or as an expression.
5328 BlockScopeRAII Scope(Info);
5329 if (const Stmt *Init = IS->getInit()) {
5330 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5331 if (ESR != ESR_Succeeded) {
5332 if (ESR != ESR_Failed && !Scope.destroy())
5333 return ESR_Failed;
5334 return ESR;
5335 }
5336 }
5337 bool Cond;
5338 if (IS->isConsteval()) {
5339 Cond = IS->isNonNegatedConsteval();
5340 // If we are not in a constant context, if consteval should not evaluate
5341 // to true.
5342 if (!Info.InConstantContext)
5343 Cond = !Cond;
5344 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5345 Cond))
5346 return ESR_Failed;
5347
5348 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5349 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5350 if (ESR != ESR_Succeeded) {
5351 if (ESR != ESR_Failed && !Scope.destroy())
5352 return ESR_Failed;
5353 return ESR;
5354 }
5355 }
5356 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5357 }
5358
5359 case Stmt::WhileStmtClass: {
5360 const WhileStmt *WS = cast<WhileStmt>(S);
5361 while (true) {
5362 BlockScopeRAII Scope(Info);
5363 bool Continue;
5364 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5365 Continue))
5366 return ESR_Failed;
5367 if (!Continue)
5368 break;
5369
5370 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5371 if (ESR != ESR_Continue) {
5372 if (ESR != ESR_Failed && !Scope.destroy())
5373 return ESR_Failed;
5374 return ESR;
5375 }
5376 if (!Scope.destroy())
5377 return ESR_Failed;
5378 }
5379 return ESR_Succeeded;
5380 }
5381
5382 case Stmt::DoStmtClass: {
5383 const DoStmt *DS = cast<DoStmt>(S);
5384 bool Continue;
5385 do {
5386 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5387 if (ESR != ESR_Continue)
5388 return ESR;
5389 Case = nullptr;
5390
5391 if (DS->getCond()->isValueDependent()) {
5392 EvaluateDependentExpr(DS->getCond(), Info);
5393 // Bailout as we don't know whether to keep going or terminate the loop.
5394 return ESR_Failed;
5395 }
5396 FullExpressionRAII CondScope(Info);
5397 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5398 !CondScope.destroy())
5399 return ESR_Failed;
5400 } while (Continue);
5401 return ESR_Succeeded;
5402 }
5403
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())
5411 return ESR_Failed;
5412 return ESR;
5413 }
5414 }
5415 while (true) {
5416 BlockScopeRAII IterScope(Info);
5417 bool Continue = true;
5418 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5419 FS->getCond(), Continue))
5420 return ESR_Failed;
5421 if (!Continue)
5422 break;
5423
5424 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5425 if (ESR != ESR_Continue) {
5426 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5427 return ESR_Failed;
5428 return ESR;
5429 }
5430
5431 if (const auto *Inc = FS->getInc()) {
5432 if (Inc->isValueDependent()) {
5433 if (!EvaluateDependentExpr(Inc, Info))
5434 return ESR_Failed;
5435 } else {
5436 FullExpressionRAII IncScope(Info);
5437 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5438 return ESR_Failed;
5439 }
5440 }
5441
5442 if (!IterScope.destroy())
5443 return ESR_Failed;
5444 }
5445 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5446 }
5447
5448 case Stmt::CXXForRangeStmtClass: {
5449 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5450 BlockScopeRAII Scope(Info);
5451
5452 // Evaluate the init-statement if present.
5453 if (FS->getInit()) {
5454 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5455 if (ESR != ESR_Succeeded) {
5456 if (ESR != ESR_Failed && !Scope.destroy())
5457 return ESR_Failed;
5458 return ESR;
5459 }
5460 }
5461
5462 // Initialize the __range variable.
5463 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5464 if (ESR != ESR_Succeeded) {
5465 if (ESR != ESR_Failed && !Scope.destroy())
5466 return ESR_Failed;
5467 return ESR;
5468 }
5469
5470 // In error-recovery cases it's possible to get here even if we failed to
5471 // synthesize the __begin and __end variables.
5472 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5473 return ESR_Failed;
5474
5475 // Create the __begin and __end iterators.
5476 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5477 if (ESR != ESR_Succeeded) {
5478 if (ESR != ESR_Failed && !Scope.destroy())
5479 return ESR_Failed;
5480 return ESR;
5481 }
5482 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5483 if (ESR != ESR_Succeeded) {
5484 if (ESR != ESR_Failed && !Scope.destroy())
5485 return ESR_Failed;
5486 return ESR;
5487 }
5488
5489 while (true) {
5490 // Condition: __begin != __end.
5491 {
5492 if (FS->getCond()->isValueDependent()) {
5493 EvaluateDependentExpr(FS->getCond(), Info);
5494 // We don't know whether to keep going or terminate the loop.
5495 return ESR_Failed;
5496 }
5497 bool Continue = true;
5498 FullExpressionRAII CondExpr(Info);
5499 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5500 return ESR_Failed;
5501 if (!Continue)
5502 break;
5503 }
5504
5505 // User's variable declaration, initialized by *__begin.
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()))
5510 return ESR_Failed;
5511 return ESR;
5512 }
5513
5514 // Loop body.
5515 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5516 if (ESR != ESR_Continue) {
5517 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5518 return ESR_Failed;
5519 return ESR;
5520 }
5521 if (FS->getInc()->isValueDependent()) {
5522 if (!EvaluateDependentExpr(FS->getInc(), Info))
5523 return ESR_Failed;
5524 } else {
5525 // Increment: ++__begin
5526 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5527 return ESR_Failed;
5528 }
5529
5530 if (!InnerScope.destroy())
5531 return ESR_Failed;
5532 }
5533
5534 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5535 }
5536
5537 case Stmt::SwitchStmtClass:
5538 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5539
5540 case Stmt::ContinueStmtClass:
5541 return ESR_Continue;
5542
5543 case Stmt::BreakStmtClass:
5544 return ESR_Break;
5545
5546 case Stmt::LabelStmtClass:
5547 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5548
5549 case Stmt::AttributedStmtClass:
5550 // As a general principle, C++11 attributes can be ignored without
5551 // any semantic impact.
5552 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5553 Case);
5554
5555 case Stmt::CaseStmtClass:
5556 case Stmt::DefaultStmtClass:
5557 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5558 case Stmt::CXXTryStmtClass:
5559 // Evaluate try blocks by evaluating all sub statements.
5560 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5561 }
5562}
5563
5564/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5565/// default constructor. If so, we'll fold it whether or not it's marked as
5566/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5567/// so we need special handling.
5568static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5569 const CXXConstructorDecl *CD,
5570 bool IsValueInitialization) {
5571 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5572 return false;
5573
5574 // Value-initialization does not call a trivial default constructor, so such a
5575 // call is a core constant expression whether or not the constructor is
5576 // constexpr.
5577 if (!CD->isConstexpr() && !IsValueInitialization) {
5578 if (Info.getLangOpts().CPlusPlus11) {
5579 // FIXME: If DiagDecl is an implicitly-declared special member function,
5580 // we should be much more explicit about why it's not constexpr.
5581 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5582 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5583 Info.Note(CD->getLocation(), diag::note_declared_at);
5584 } else {
5585 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5586 }
5587 }
5588 return true;
5589}
5590
5591/// CheckConstexprFunction - Check that a function can be called in a constant
5592/// expression.
5593static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5595 const FunctionDecl *Definition,
5596 const Stmt *Body) {
5597 // Potential constant expressions can contain calls to declared, but not yet
5598 // defined, constexpr functions.
5599 if (Info.checkingPotentialConstantExpression() && !