Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 6196, column 28
Address of stack memory associated with local variable 'Frame' is still referred to by the stack variable 'Info' upon returning to the caller. This will be a dangling reference

Annotated Source Code

Press '?' to see keyboard shortcuts

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