Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 9954, column 3
Called C++ object pointer is null

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