Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 9948, 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~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -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-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/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 return false;
1983
1984 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
1985 A.getLValueVersion() == B.getLValueVersion();
1986}
1987
1988static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1989 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 1989, __PRETTY_FUNCTION__))
;
1990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1991 if (VD)
1992 Info.Note(VD->getLocation(), diag::note_declared_at);
1993 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1994 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1995 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1996 // FIXME: Produce a note for dangling pointers too.
1997 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1998 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1999 diag::note_constexpr_dynamic_alloc_here);
2000 }
2001 // We have no information to show for a typeid(T) object.
2002}
2003
2004enum class CheckEvaluationResultKind {
2005 ConstantExpression,
2006 FullyInitialized,
2007};
2008
2009/// Materialized temporaries that we've already checked to determine if they're
2010/// initializsed by a constant expression.
2011using CheckedTemporaries =
2012 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2013
2014static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2015 EvalInfo &Info, SourceLocation DiagLoc,
2016 QualType Type, const APValue &Value,
2017 Expr::ConstExprUsage Usage,
2018 SourceLocation SubobjectLoc,
2019 CheckedTemporaries &CheckedTemps);
2020
2021/// Check that this reference or pointer core constant expression is a valid
2022/// value for an address or reference constant expression. Return true if we
2023/// can fold this expression, whether or not it's a constant expression.
2024static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2025 QualType Type, const LValue &LVal,
2026 Expr::ConstExprUsage Usage,
2027 CheckedTemporaries &CheckedTemps) {
2028 bool IsReferenceType = Type->isReferenceType();
2029
2030 APValue::LValueBase Base = LVal.getLValueBase();
2031 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2032
2033 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2034 if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2035 if (FD->isConsteval()) {
2036 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2037 << !Type->isAnyPointerType();
2038 Info.Note(FD->getLocation(), diag::note_declared_at);
2039 return false;
2040 }
2041 }
2042 }
2043
2044 // Check that the object is a global. Note that the fake 'this' object we
2045 // manufacture when checking potential constant expressions is conservatively
2046 // assumed to be global here.
2047 if (!IsGlobalLValue(Base)) {
2048 if (Info.getLangOpts().CPlusPlus11) {
2049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2050 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2051 << IsReferenceType << !Designator.Entries.empty()
2052 << !!VD << VD;
2053
2054 auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2055 if (VarD && VarD->isConstexpr()) {
2056 // Non-static local constexpr variables have unintuitive semantics:
2057 // constexpr int a = 1;
2058 // constexpr const int *p = &a;
2059 // ... is invalid because the address of 'a' is not constant. Suggest
2060 // adding a 'static' in this case.
2061 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2062 << VarD
2063 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2064 } else {
2065 NoteLValueLocation(Info, Base);
2066 }
2067 } else {
2068 Info.FFDiag(Loc);
2069 }
2070 // Don't allow references to temporaries to escape.
2071 return false;
2072 }
2073 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2075, __PRETTY_FUNCTION__))
2074 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2075, __PRETTY_FUNCTION__))
2075 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2075, __PRETTY_FUNCTION__))
;
2076
2077 if (Base.is<DynamicAllocLValue>()) {
2078 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2079 << IsReferenceType << !Designator.Entries.empty();
2080 NoteLValueLocation(Info, Base);
2081 return false;
2082 }
2083
2084 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2085 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2086 // Check if this is a thread-local variable.
2087 if (Var->getTLSKind())
2088 // FIXME: Diagnostic!
2089 return false;
2090
2091 // A dllimport variable never acts like a constant.
2092 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2093 // FIXME: Diagnostic!
2094 return false;
2095 }
2096 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2097 // __declspec(dllimport) must be handled very carefully:
2098 // We must never initialize an expression with the thunk in C++.
2099 // Doing otherwise would allow the same id-expression to yield
2100 // different addresses for the same function in different translation
2101 // units. However, this means that we must dynamically initialize the
2102 // expression with the contents of the import address table at runtime.
2103 //
2104 // The C language has no notion of ODR; furthermore, it has no notion of
2105 // dynamic initialization. This means that we are permitted to
2106 // perform initialization with the address of the thunk.
2107 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2108 FD->hasAttr<DLLImportAttr>())
2109 // FIXME: Diagnostic!
2110 return false;
2111 }
2112 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2113 Base.dyn_cast<const Expr *>())) {
2114 if (CheckedTemps.insert(MTE).second) {
2115 QualType TempType = getType(Base);
2116 if (TempType.isDestructedType()) {
2117 Info.FFDiag(MTE->getExprLoc(),
2118 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2119 << TempType;
2120 return false;
2121 }
2122
2123 APValue *V = MTE->getOrCreateValue(false);
2124 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2124, __PRETTY_FUNCTION__))
;
2125 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2126 Info, MTE->getExprLoc(), TempType, *V,
2127 Usage, SourceLocation(), CheckedTemps))
2128 return false;
2129 }
2130 }
2131
2132 // Allow address constant expressions to be past-the-end pointers. This is
2133 // an extension: the standard requires them to point to an object.
2134 if (!IsReferenceType)
2135 return true;
2136
2137 // A reference constant expression must refer to an object.
2138 if (!Base) {
2139 // FIXME: diagnostic
2140 Info.CCEDiag(Loc);
2141 return true;
2142 }
2143
2144 // Does this refer one past the end of some object?
2145 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2146 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2147 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2148 << !Designator.Entries.empty() << !!VD << VD;
2149 NoteLValueLocation(Info, Base);
2150 }
2151
2152 return true;
2153}
2154
2155/// Member pointers are constant expressions unless they point to a
2156/// non-virtual dllimport member function.
2157static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2158 SourceLocation Loc,
2159 QualType Type,
2160 const APValue &Value,
2161 Expr::ConstExprUsage Usage) {
2162 const ValueDecl *Member = Value.getMemberPointerDecl();
2163 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2164 if (!FD)
2165 return true;
2166 if (FD->isConsteval()) {
2167 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2168 Info.Note(FD->getLocation(), diag::note_declared_at);
2169 return false;
2170 }
2171 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2172 !FD->hasAttr<DLLImportAttr>();
2173}
2174
2175/// Check that this core constant expression is of literal type, and if not,
2176/// produce an appropriate diagnostic.
2177static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2178 const LValue *This = nullptr) {
2179 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2180 return true;
2181
2182 // C++1y: A constant initializer for an object o [...] may also invoke
2183 // constexpr constructors for o and its subobjects even if those objects
2184 // are of non-literal class types.
2185 //
2186 // C++11 missed this detail for aggregates, so classes like this:
2187 // struct foo_t { union { int i; volatile int j; } u; };
2188 // are not (obviously) initializable like so:
2189 // __attribute__((__require_constant_initialization__))
2190 // static const foo_t x = {{0}};
2191 // because "i" is a subobject with non-literal initialization (due to the
2192 // volatile member of the union). See:
2193 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2194 // Therefore, we use the C++1y behavior.
2195 if (This && Info.EvaluatingDecl == This->getLValueBase())
2196 return true;
2197
2198 // Prvalue constant expressions must be of literal types.
2199 if (Info.getLangOpts().CPlusPlus11)
2200 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2201 << E->getType();
2202 else
2203 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2204 return false;
2205}
2206
2207static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2208 EvalInfo &Info, SourceLocation DiagLoc,
2209 QualType Type, const APValue &Value,
2210 Expr::ConstExprUsage Usage,
2211 SourceLocation SubobjectLoc,
2212 CheckedTemporaries &CheckedTemps) {
2213 if (!Value.hasValue()) {
2214 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2215 << true << Type;
2216 if (SubobjectLoc.isValid())
2217 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2218 return false;
2219 }
2220
2221 // We allow _Atomic(T) to be initialized from anything that T can be
2222 // initialized from.
2223 if (const AtomicType *AT = Type->getAs<AtomicType>())
2224 Type = AT->getValueType();
2225
2226 // Core issue 1454: For a literal constant expression of array or class type,
2227 // each subobject of its value shall have been initialized by a constant
2228 // expression.
2229 if (Value.isArray()) {
2230 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2231 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2232 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2233 Value.getArrayInitializedElt(I), Usage,
2234 SubobjectLoc, CheckedTemps))
2235 return false;
2236 }
2237 if (!Value.hasArrayFiller())
2238 return true;
2239 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2240 Value.getArrayFiller(), Usage, SubobjectLoc,
2241 CheckedTemps);
2242 }
2243 if (Value.isUnion() && Value.getUnionField()) {
2244 return CheckEvaluationResult(
2245 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2246 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2247 CheckedTemps);
2248 }
2249 if (Value.isStruct()) {
2250 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2251 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2252 unsigned BaseIndex = 0;
2253 for (const CXXBaseSpecifier &BS : CD->bases()) {
2254 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2255 Value.getStructBase(BaseIndex), Usage,
2256 BS.getBeginLoc(), CheckedTemps))
2257 return false;
2258 ++BaseIndex;
2259 }
2260 }
2261 for (const auto *I : RD->fields()) {
2262 if (I->isUnnamedBitfield())
2263 continue;
2264
2265 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2266 Value.getStructField(I->getFieldIndex()),
2267 Usage, I->getLocation(), CheckedTemps))
2268 return false;
2269 }
2270 }
2271
2272 if (Value.isLValue() &&
2273 CERK == CheckEvaluationResultKind::ConstantExpression) {
2274 LValue LVal;
2275 LVal.setFrom(Info.Ctx, Value);
2276 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2277 CheckedTemps);
2278 }
2279
2280 if (Value.isMemberPointer() &&
2281 CERK == CheckEvaluationResultKind::ConstantExpression)
2282 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2283
2284 // Everything else is fine.
2285 return true;
2286}
2287
2288/// Check that this core constant expression value is a valid value for a
2289/// constant expression. If not, report an appropriate diagnostic. Does not
2290/// check that the expression is of literal type.
2291static bool
2292CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2293 const APValue &Value,
2294 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2295 // Nothing to check for a constant expression of type 'cv void'.
2296 if (Type->isVoidType())
2297 return true;
2298
2299 CheckedTemporaries CheckedTemps;
2300 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2301 Info, DiagLoc, Type, Value, Usage,
2302 SourceLocation(), CheckedTemps);
2303}
2304
2305/// Check that this evaluated value is fully-initialized and can be loaded by
2306/// an lvalue-to-rvalue conversion.
2307static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2308 QualType Type, const APValue &Value) {
2309 CheckedTemporaries CheckedTemps;
2310 return CheckEvaluationResult(
2311 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2312 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2313}
2314
2315/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2316/// "the allocated storage is deallocated within the evaluation".
2317static bool CheckMemoryLeaks(EvalInfo &Info) {
2318 if (!Info.HeapAllocs.empty()) {
2319 // We can still fold to a constant despite a compile-time memory leak,
2320 // so long as the heap allocation isn't referenced in the result (we check
2321 // that in CheckConstantExpression).
2322 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2323 diag::note_constexpr_memory_leak)
2324 << unsigned(Info.HeapAllocs.size() - 1);
2325 }
2326 return true;
2327}
2328
2329static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2330 // A null base expression indicates a null pointer. These are always
2331 // evaluatable, and they are false unless the offset is zero.
2332 if (!Value.getLValueBase()) {
2333 Result = !Value.getLValueOffset().isZero();
2334 return true;
2335 }
2336
2337 // We have a non-null base. These are generally known to be true, but if it's
2338 // a weak declaration it can be null at runtime.
2339 Result = true;
2340 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2341 return !Decl || !Decl->isWeak();
2342}
2343
2344static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2345 switch (Val.getKind()) {
2346 case APValue::None:
2347 case APValue::Indeterminate:
2348 return false;
2349 case APValue::Int:
2350 Result = Val.getInt().getBoolValue();
2351 return true;
2352 case APValue::FixedPoint:
2353 Result = Val.getFixedPoint().getBoolValue();
2354 return true;
2355 case APValue::Float:
2356 Result = !Val.getFloat().isZero();
2357 return true;
2358 case APValue::ComplexInt:
2359 Result = Val.getComplexIntReal().getBoolValue() ||
2360 Val.getComplexIntImag().getBoolValue();
2361 return true;
2362 case APValue::ComplexFloat:
2363 Result = !Val.getComplexFloatReal().isZero() ||
2364 !Val.getComplexFloatImag().isZero();
2365 return true;
2366 case APValue::LValue:
2367 return EvalPointerValueAsBool(Val, Result);
2368 case APValue::MemberPointer:
2369 Result = Val.getMemberPointerDecl();
2370 return true;
2371 case APValue::Vector:
2372 case APValue::Array:
2373 case APValue::Struct:
2374 case APValue::Union:
2375 case APValue::AddrLabelDiff:
2376 return false;
2377 }
2378
2379 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2379)
;
2380}
2381
2382static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2383 EvalInfo &Info) {
2384 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2384, __PRETTY_FUNCTION__))
;
2385 APValue Val;
2386 if (!Evaluate(Val, Info, E))
2387 return false;
2388 return HandleConversionToBool(Val, Result);
2389}
2390
2391template<typename T>
2392static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2393 const T &SrcValue, QualType DestType) {
2394 Info.CCEDiag(E, diag::note_constexpr_overflow)
2395 << SrcValue << DestType;
2396 return Info.noteUndefinedBehavior();
2397}
2398
2399static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2400 QualType SrcType, const APFloat &Value,
2401 QualType DestType, APSInt &Result) {
2402 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2403 // Determine whether we are converting to unsigned or signed.
2404 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2405
2406 Result = APSInt(DestWidth, !DestSigned);
2407 bool ignored;
2408 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2409 & APFloat::opInvalidOp)
2410 return HandleOverflow(Info, E, Value, DestType);
2411 return true;
2412}
2413
2414static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2415 QualType SrcType, QualType DestType,
2416 APFloat &Result) {
2417 APFloat Value = Result;
2418 bool ignored;
2419 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2420 APFloat::rmNearestTiesToEven, &ignored);
2421 return true;
2422}
2423
2424static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2425 QualType DestType, QualType SrcType,
2426 const APSInt &Value) {
2427 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2428 // Figure out if this is a truncate, extend or noop cast.
2429 // If the input is signed, do a sign extend, noop, or truncate.
2430 APSInt Result = Value.extOrTrunc(DestWidth);
2431 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2432 if (DestType->isBooleanType())
2433 Result = Value.getBoolValue();
2434 return Result;
2435}
2436
2437static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2438 QualType SrcType, const APSInt &Value,
2439 QualType DestType, APFloat &Result) {
2440 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2441 Result.convertFromAPInt(Value, Value.isSigned(),
2442 APFloat::rmNearestTiesToEven);
2443 return true;
2444}
2445
2446static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2447 APValue &Value, const FieldDecl *FD) {
2448 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2448, __PRETTY_FUNCTION__))
;
2449
2450 if (!Value.isInt()) {
2451 // Trying to store a pointer-cast-to-integer into a bitfield.
2452 // FIXME: In this case, we should provide the diagnostic for casting
2453 // a pointer to an integer.
2454 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2454, __PRETTY_FUNCTION__))
;
2455 Info.FFDiag(E);
2456 return false;
2457 }
2458
2459 APSInt &Int = Value.getInt();
2460 unsigned OldBitWidth = Int.getBitWidth();
2461 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2462 if (NewBitWidth < OldBitWidth)
2463 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2464 return true;
2465}
2466
2467static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2468 llvm::APInt &Res) {
2469 APValue SVal;
2470 if (!Evaluate(SVal, Info, E))
2471 return false;
2472 if (SVal.isInt()) {
2473 Res = SVal.getInt();
2474 return true;
2475 }
2476 if (SVal.isFloat()) {
2477 Res = SVal.getFloat().bitcastToAPInt();
2478 return true;
2479 }
2480 if (SVal.isVector()) {
2481 QualType VecTy = E->getType();
2482 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2483 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2484 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2485 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2486 Res = llvm::APInt::getNullValue(VecSize);
2487 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2488 APValue &Elt = SVal.getVectorElt(i);
2489 llvm::APInt EltAsInt;
2490 if (Elt.isInt()) {
2491 EltAsInt = Elt.getInt();
2492 } else if (Elt.isFloat()) {
2493 EltAsInt = Elt.getFloat().bitcastToAPInt();
2494 } else {
2495 // Don't try to handle vectors of anything other than int or float
2496 // (not sure if it's possible to hit this case).
2497 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2498 return false;
2499 }
2500 unsigned BaseEltSize = EltAsInt.getBitWidth();
2501 if (BigEndian)
2502 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2503 else
2504 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2505 }
2506 return true;
2507 }
2508 // Give up if the input isn't an int, float, or vector. For example, we
2509 // reject "(v4i16)(intptr_t)&a".
2510 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2511 return false;
2512}
2513
2514/// Perform the given integer operation, which is known to need at most BitWidth
2515/// bits, and check for overflow in the original type (if that type was not an
2516/// unsigned type).
2517template<typename Operation>
2518static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2519 const APSInt &LHS, const APSInt &RHS,
2520 unsigned BitWidth, Operation Op,
2521 APSInt &Result) {
2522 if (LHS.isUnsigned()) {
2523 Result = Op(LHS, RHS);
2524 return true;
2525 }
2526
2527 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2528 Result = Value.trunc(LHS.getBitWidth());
2529 if (Result.extend(BitWidth) != Value) {
2530 if (Info.checkingForUndefinedBehavior())
2531 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2532 diag::warn_integer_constant_overflow)
2533 << Result.toString(10) << E->getType();
2534 else
2535 return HandleOverflow(Info, E, Value, E->getType());
2536 }
2537 return true;
2538}
2539
2540/// Perform the given binary integer operation.
2541static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2542 BinaryOperatorKind Opcode, APSInt RHS,
2543 APSInt &Result) {
2544 switch (Opcode) {
2545 default:
2546 Info.FFDiag(E);
2547 return false;
2548 case BO_Mul:
2549 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2550 std::multiplies<APSInt>(), Result);
2551 case BO_Add:
2552 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2553 std::plus<APSInt>(), Result);
2554 case BO_Sub:
2555 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2556 std::minus<APSInt>(), Result);
2557 case BO_And: Result = LHS & RHS; return true;
2558 case BO_Xor: Result = LHS ^ RHS; return true;
2559 case BO_Or: Result = LHS | RHS; return true;
2560 case BO_Div:
2561 case BO_Rem:
2562 if (RHS == 0) {
2563 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2564 return false;
2565 }
2566 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2567 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2568 // this operation and gives the two's complement result.
2569 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2570 LHS.isSigned() && LHS.isMinSignedValue())
2571 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2572 E->getType());
2573 return true;
2574 case BO_Shl: {
2575 if (Info.getLangOpts().OpenCL)
2576 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2577 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2578 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2579 RHS.isUnsigned());
2580 else if (RHS.isSigned() && RHS.isNegative()) {
2581 // During constant-folding, a negative shift is an opposite shift. Such
2582 // a shift is not a constant expression.
2583 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2584 RHS = -RHS;
2585 goto shift_right;
2586 }
2587 shift_left:
2588 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2589 // the shifted type.
2590 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2591 if (SA != RHS) {
2592 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2593 << RHS << E->getType() << LHS.getBitWidth();
2594 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2595 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2596 // operand, and must not overflow the corresponding unsigned type.
2597 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2598 // E1 x 2^E2 module 2^N.
2599 if (LHS.isNegative())
2600 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2601 else if (LHS.countLeadingZeros() < SA)
2602 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2603 }
2604 Result = LHS << SA;
2605 return true;
2606 }
2607 case BO_Shr: {
2608 if (Info.getLangOpts().OpenCL)
2609 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2610 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2611 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2612 RHS.isUnsigned());
2613 else if (RHS.isSigned() && RHS.isNegative()) {
2614 // During constant-folding, a negative shift is an opposite shift. Such a
2615 // shift is not a constant expression.
2616 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2617 RHS = -RHS;
2618 goto shift_left;
2619 }
2620 shift_right:
2621 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2622 // shifted type.
2623 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2624 if (SA != RHS)
2625 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2626 << RHS << E->getType() << LHS.getBitWidth();
2627 Result = LHS >> SA;
2628 return true;
2629 }
2630
2631 case BO_LT: Result = LHS < RHS; return true;
2632 case BO_GT: Result = LHS > RHS; return true;
2633 case BO_LE: Result = LHS <= RHS; return true;
2634 case BO_GE: Result = LHS >= RHS; return true;
2635 case BO_EQ: Result = LHS == RHS; return true;
2636 case BO_NE: Result = LHS != RHS; return true;
2637 case BO_Cmp:
2638 llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2638)
;
2639 }
2640}
2641
2642/// Perform the given binary floating-point operation, in-place, on LHS.
2643static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2644 APFloat &LHS, BinaryOperatorKind Opcode,
2645 const APFloat &RHS) {
2646 switch (Opcode) {
2647 default:
2648 Info.FFDiag(E);
2649 return false;
2650 case BO_Mul:
2651 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2652 break;
2653 case BO_Add:
2654 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2655 break;
2656 case BO_Sub:
2657 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2658 break;
2659 case BO_Div:
2660 // [expr.mul]p4:
2661 // If the second operand of / or % is zero the behavior is undefined.
2662 if (RHS.isZero())
2663 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2664 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2665 break;
2666 }
2667
2668 // [expr.pre]p4:
2669 // If during the evaluation of an expression, the result is not
2670 // mathematically defined [...], the behavior is undefined.
2671 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2672 if (LHS.isNaN()) {
2673 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2674 return Info.noteUndefinedBehavior();
2675 }
2676 return true;
2677}
2678
2679static bool handleLogicalOpForVector(const APInt &LHSValue,
2680 BinaryOperatorKind Opcode,
2681 const APInt &RHSValue, APInt &Result) {
2682 bool LHS = (LHSValue != 0);
2683 bool RHS = (RHSValue != 0);
2684
2685 if (Opcode == BO_LAnd)
2686 Result = LHS && RHS;
2687 else
2688 Result = LHS || RHS;
2689 return true;
2690}
2691static bool handleLogicalOpForVector(const APFloat &LHSValue,
2692 BinaryOperatorKind Opcode,
2693 const APFloat &RHSValue, APInt &Result) {
2694 bool LHS = !LHSValue.isZero();
2695 bool RHS = !RHSValue.isZero();
2696
2697 if (Opcode == BO_LAnd)
2698 Result = LHS && RHS;
2699 else
2700 Result = LHS || RHS;
2701 return true;
2702}
2703
2704static bool handleLogicalOpForVector(const APValue &LHSValue,
2705 BinaryOperatorKind Opcode,
2706 const APValue &RHSValue, APInt &Result) {
2707 // The result is always an int type, however operands match the first.
2708 if (LHSValue.getKind() == APValue::Int)
2709 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2710 RHSValue.getInt(), Result);
2711 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2711, __PRETTY_FUNCTION__))
;
2712 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2713 RHSValue.getFloat(), Result);
2714}
2715
2716template <typename APTy>
2717static bool
2718handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2719 const APTy &RHSValue, APInt &Result) {
2720 switch (Opcode) {
2721 default:
2722 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2722)
;
2723 case BO_EQ:
2724 Result = (LHSValue == RHSValue);
2725 break;
2726 case BO_NE:
2727 Result = (LHSValue != RHSValue);
2728 break;
2729 case BO_LT:
2730 Result = (LHSValue < RHSValue);
2731 break;
2732 case BO_GT:
2733 Result = (LHSValue > RHSValue);
2734 break;
2735 case BO_LE:
2736 Result = (LHSValue <= RHSValue);
2737 break;
2738 case BO_GE:
2739 Result = (LHSValue >= RHSValue);
2740 break;
2741 }
2742
2743 return true;
2744}
2745
2746static bool handleCompareOpForVector(const APValue &LHSValue,
2747 BinaryOperatorKind Opcode,
2748 const APValue &RHSValue, APInt &Result) {
2749 // The result is always an int type, however operands match the first.
2750 if (LHSValue.getKind() == APValue::Int)
2751 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2752 RHSValue.getInt(), Result);
2753 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2753, __PRETTY_FUNCTION__))
;
2754 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2755 RHSValue.getFloat(), Result);
2756}
2757
2758// Perform binary operations for vector types, in place on the LHS.
2759static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E,
2760 BinaryOperatorKind Opcode,
2761 APValue &LHSValue,
2762 const APValue &RHSValue) {
2763 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2764, __PRETTY_FUNCTION__))
2764 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2764, __PRETTY_FUNCTION__))
;
2765
2766 const auto *VT = E->getType()->castAs<VectorType>();
2767 unsigned NumElements = VT->getNumElements();
2768 QualType EltTy = VT->getElementType();
2769
2770 // In the cases (typically C as I've observed) where we aren't evaluating
2771 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2772 // just give up.
2773 if (!LHSValue.isVector()) {
2774 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2775, __PRETTY_FUNCTION__))
2775 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2775, __PRETTY_FUNCTION__))
;
2776 Info.FFDiag(E);
2777 return false;
2778 }
2779
2780 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2781, __PRETTY_FUNCTION__))
2781 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2781, __PRETTY_FUNCTION__))
;
2782
2783 SmallVector<APValue, 4> ResultElements;
2784
2785 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2786 APValue LHSElt = LHSValue.getVectorElt(EltNum);
2787 APValue RHSElt = RHSValue.getVectorElt(EltNum);
2788
2789 if (EltTy->isIntegerType()) {
2790 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2791 EltTy->isUnsignedIntegerType()};
2792 bool Success = true;
2793
2794 if (BinaryOperator::isLogicalOp(Opcode))
2795 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2796 else if (BinaryOperator::isComparisonOp(Opcode))
2797 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2798 else
2799 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2800 RHSElt.getInt(), EltResult);
2801
2802 if (!Success) {
2803 Info.FFDiag(E);
2804 return false;
2805 }
2806 ResultElements.emplace_back(EltResult);
2807
2808 } else if (EltTy->isFloatingType()) {
2809 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2811, __PRETTY_FUNCTION__))
2810 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2811, __PRETTY_FUNCTION__))
2811 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2811, __PRETTY_FUNCTION__))
;
2812 APFloat LHSFloat = LHSElt.getFloat();
2813
2814 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2815 RHSElt.getFloat())) {
2816 Info.FFDiag(E);
2817 return false;
2818 }
2819
2820 ResultElements.emplace_back(LHSFloat);
2821 }
2822 }
2823
2824 LHSValue = APValue(ResultElements.data(), ResultElements.size());
2825 return true;
2826}
2827
2828/// Cast an lvalue referring to a base subobject to a derived class, by
2829/// truncating the lvalue's path to the given length.
2830static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2831 const RecordDecl *TruncatedType,
2832 unsigned TruncatedElements) {
2833 SubobjectDesignator &D = Result.Designator;
2834
2835 // Check we actually point to a derived class object.
2836 if (TruncatedElements == D.Entries.size())
2837 return true;
2838 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2839, __PRETTY_FUNCTION__))
2839 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2839, __PRETTY_FUNCTION__))
;
2840 if (!Result.checkSubobject(Info, E, CSK_Derived))
2841 return false;
2842
2843 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2844 const RecordDecl *RD = TruncatedType;
2845 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2846 if (RD->isInvalidDecl()) return false;
2847 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2848 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2849 if (isVirtualBaseClass(D.Entries[I]))
2850 Result.Offset -= Layout.getVBaseClassOffset(Base);
2851 else
2852 Result.Offset -= Layout.getBaseClassOffset(Base);
2853 RD = Base;
2854 }
2855 D.Entries.resize(TruncatedElements);
2856 return true;
2857}
2858
2859static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2860 const CXXRecordDecl *Derived,
2861 const CXXRecordDecl *Base,
2862 const ASTRecordLayout *RL = nullptr) {
2863 if (!RL) {
2864 if (Derived->isInvalidDecl()) return false;
2865 RL = &Info.Ctx.getASTRecordLayout(Derived);
2866 }
2867
2868 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2869 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2870 return true;
2871}
2872
2873static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2874 const CXXRecordDecl *DerivedDecl,
2875 const CXXBaseSpecifier *Base) {
2876 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2877
2878 if (!Base->isVirtual())
2879 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2880
2881 SubobjectDesignator &D = Obj.Designator;
2882 if (D.Invalid)
2883 return false;
2884
2885 // Extract most-derived object and corresponding type.
2886 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2887 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2888 return false;
2889
2890 // Find the virtual base class.
2891 if (DerivedDecl->isInvalidDecl()) return false;
2892 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2893 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2894 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2895 return true;
2896}
2897
2898static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2899 QualType Type, LValue &Result) {
2900 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2901 PathE = E->path_end();
2902 PathI != PathE; ++PathI) {
2903 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2904 *PathI))
2905 return false;
2906 Type = (*PathI)->getType();
2907 }
2908 return true;
2909}
2910
2911/// Cast an lvalue referring to a derived class to a known base subobject.
2912static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2913 const CXXRecordDecl *DerivedRD,
2914 const CXXRecordDecl *BaseRD) {
2915 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2916 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2917 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2918 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 2918)
;
2919
2920 for (CXXBasePathElement &Elem : Paths.front())
2921 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2922 return false;
2923 return true;
2924}
2925
2926/// Update LVal to refer to the given field, which must be a member of the type
2927/// currently described by LVal.
2928static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2929 const FieldDecl *FD,
2930 const ASTRecordLayout *RL = nullptr) {
2931 if (!RL) {
2932 if (FD->getParent()->isInvalidDecl()) return false;
2933 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2934 }
2935
2936 unsigned I = FD->getFieldIndex();
2937 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2938 LVal.addDecl(Info, E, FD);
2939 return true;
2940}
2941
2942/// Update LVal to refer to the given indirect field.
2943static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2944 LValue &LVal,
2945 const IndirectFieldDecl *IFD) {
2946 for (const auto *C : IFD->chain())
2947 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2948 return false;
2949 return true;
2950}
2951
2952/// Get the size of the given type in char units.
2953static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2954 QualType Type, CharUnits &Size) {
2955 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2956 // extension.
2957 if (Type->isVoidType() || Type->isFunctionType()) {
2958 Size = CharUnits::One();
2959 return true;
2960 }
2961
2962 if (Type->isDependentType()) {
2963 Info.FFDiag(Loc);
2964 return false;
2965 }
2966
2967 if (!Type->isConstantSizeType()) {
2968 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2969 // FIXME: Better diagnostic.
2970 Info.FFDiag(Loc);
2971 return false;
2972 }
2973
2974 Size = Info.Ctx.getTypeSizeInChars(Type);
2975 return true;
2976}
2977
2978/// Update a pointer value to model pointer arithmetic.
2979/// \param Info - Information about the ongoing evaluation.
2980/// \param E - The expression being evaluated, for diagnostic purposes.
2981/// \param LVal - The pointer value to be updated.
2982/// \param EltTy - The pointee type represented by LVal.
2983/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2984static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2985 LValue &LVal, QualType EltTy,
2986 APSInt Adjustment) {
2987 CharUnits SizeOfPointee;
2988 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2989 return false;
2990
2991 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2992 return true;
2993}
2994
2995static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2996 LValue &LVal, QualType EltTy,
2997 int64_t Adjustment) {
2998 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2999 APSInt::get(Adjustment));
3000}
3001
3002/// Update an lvalue to refer to a component of a complex number.
3003/// \param Info - Information about the ongoing evaluation.
3004/// \param LVal - The lvalue to be updated.
3005/// \param EltTy - The complex number's component type.
3006/// \param Imag - False for the real component, true for the imaginary.
3007static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3008 LValue &LVal, QualType EltTy,
3009 bool Imag) {
3010 if (Imag) {
3011 CharUnits SizeOfComponent;
3012 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3013 return false;
3014 LVal.Offset += SizeOfComponent;
3015 }
3016 LVal.addComplex(Info, E, EltTy, Imag);
3017 return true;
3018}
3019
3020/// Try to evaluate the initializer for a variable declaration.
3021///
3022/// \param Info Information about the ongoing evaluation.
3023/// \param E An expression to be used when printing diagnostics.
3024/// \param VD The variable whose initializer should be obtained.
3025/// \param Frame The frame in which the variable was created. Must be null
3026/// if this variable is not local to the evaluation.
3027/// \param Result Filled in with a pointer to the value of the variable.
3028static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3029 const VarDecl *VD, CallStackFrame *Frame,
3030 APValue *&Result, const LValue *LVal) {
3031
3032 // If this is a parameter to an active constexpr function call, perform
3033 // argument substitution.
3034 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3035 // Assume arguments of a potential constant expression are unknown
3036 // constant expressions.
3037 if (Info.checkingPotentialConstantExpression())
3038 return false;
3039 if (!Frame || !Frame->Arguments) {
3040 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD;
3041 return false;
3042 }
3043 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3044 return true;
3045 }
3046
3047 // If this is a local variable, dig out its value.
3048 if (Frame) {
3049 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3050 : Frame->getCurrentTemporary(VD);
3051 if (!Result) {
3052 // Assume variables referenced within a lambda's call operator that were
3053 // not declared within the call operator are captures and during checking
3054 // of a potential constant expression, assume they are unknown constant
3055 // expressions.
3056 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3058, __PRETTY_FUNCTION__))
3057 (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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3058, __PRETTY_FUNCTION__))
3058 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3058, __PRETTY_FUNCTION__))
;
3059 if (Info.checkingPotentialConstantExpression())
3060 return false;
3061 // FIXME: implement capture evaluation during constant expr evaluation.
3062 Info.FFDiag(E->getBeginLoc(),
3063 diag::note_unimplemented_constexpr_lambda_feature_ast)
3064 << "captures not currently allowed";
3065 return false;
3066 }
3067 return true;
3068 }
3069
3070 // Dig out the initializer, and use the declaration which it's attached to.
3071 // FIXME: We should eventually check whether the variable has a reachable
3072 // initializing declaration.
3073 const Expr *Init = VD->getAnyInitializer(VD);
3074 if (!Init) {
3075 // Don't diagnose during potential constant expression checking; an
3076 // initializer might be added later.
3077 if (!Info.checkingPotentialConstantExpression()) {
3078 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3079 << VD;
3080 Info.Note(VD->getLocation(), diag::note_declared_at);
3081 }
3082 return false;
3083 }
3084
3085 if (Init->isValueDependent()) {
3086 // The DeclRefExpr is not value-dependent, but the variable it refers to
3087 // has a value-dependent initializer. This should only happen in
3088 // constant-folding cases, where the variable is not actually of a suitable
3089 // type for use in a constant expression (otherwise the DeclRefExpr would
3090 // have been value-dependent too), so diagnose that.
3091 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))((!VD->mightBeUsableInConstantExpressions(Info.Ctx)) ? static_cast
<void> (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3091, __PRETTY_FUNCTION__))
;
3092 if (!Info.checkingPotentialConstantExpression()) {
3093 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3094 ? diag::note_constexpr_ltor_non_constexpr
3095 : diag::note_constexpr_ltor_non_integral, 1)
3096 << VD << VD->getType();
3097 Info.Note(VD->getLocation(), diag::note_declared_at);
3098 }
3099 return false;
3100 }
3101
3102 // If we're currently evaluating the initializer of this declaration, use that
3103 // in-flight value.
3104 if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(),
3105 VD)) {
3106 Result = Info.EvaluatingDeclValue;
3107 return true;
3108 }
3109
3110 // Check that we can fold the initializer. In C++, we will have already done
3111 // this in the cases where it matters for conformance.
3112 SmallVector<PartialDiagnosticAt, 8> Notes;
3113 if (!VD->evaluateValue(Notes)) {
3114 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3115 Notes.size() + 1) << VD;
3116 Info.Note(VD->getLocation(), diag::note_declared_at);
3117 Info.addNotes(Notes);
3118 return false;
3119 }
3120
3121 // Check that the variable is actually usable in constant expressions.
3122 if (!VD->checkInitIsICE()) {
3123 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3124 Notes.size() + 1) << VD;
3125 Info.Note(VD->getLocation(), diag::note_declared_at);
3126 Info.addNotes(Notes);
3127 }
3128
3129 // Never use the initializer of a weak variable, not even for constant
3130 // folding. We can't be sure that this is the definition that will be used.
3131 if (VD->isWeak()) {
3132 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3133 Info.Note(VD->getLocation(), diag::note_declared_at);
3134 return false;
3135 }
3136
3137 Result = VD->getEvaluatedValue();
3138 return true;
3139}
3140
3141static bool IsConstNonVolatile(QualType T) {
3142 Qualifiers Quals = T.getQualifiers();
3143 return Quals.hasConst() && !Quals.hasVolatile();
3144}
3145
3146/// Get the base index of the given base class within an APValue representing
3147/// the given derived class.
3148static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3149 const CXXRecordDecl *Base) {
3150 Base = Base->getCanonicalDecl();
3151 unsigned Index = 0;
3152 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3153 E = Derived->bases_end(); I != E; ++I, ++Index) {
3154 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3155 return Index;
3156 }
3157
3158 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3158)
;
3159}
3160
3161/// Extract the value of a character from a string literal.
3162static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3163 uint64_t Index) {
3164 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3165, __PRETTY_FUNCTION__))
3165 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3165, __PRETTY_FUNCTION__))
;
3166
3167 // FIXME: Support MakeStringConstant
3168 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3169 std::string Str;
3170 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3171 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3171, __PRETTY_FUNCTION__))
;
3172 return APSInt::getUnsigned(Str.c_str()[Index]);
3173 }
3174
3175 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3176 Lit = PE->getFunctionName();
3177 const StringLiteral *S = cast<StringLiteral>(Lit);
3178 const ConstantArrayType *CAT =
3179 Info.Ctx.getAsConstantArrayType(S->getType());
3180 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3180, __PRETTY_FUNCTION__))
;
3181 QualType CharType = CAT->getElementType();
3182 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3182, __PRETTY_FUNCTION__))
;
3183
3184 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3185 CharType->isUnsignedIntegerType());
3186 if (Index < S->getLength())
3187 Value = S->getCodeUnit(Index);
3188 return Value;
3189}
3190
3191// Expand a string literal into an array of characters.
3192//
3193// FIXME: This is inefficient; we should probably introduce something similar
3194// to the LLVM ConstantDataArray to make this cheaper.
3195static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3196 APValue &Result,
3197 QualType AllocType = QualType()) {
3198 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3199 AllocType.isNull() ? S->getType() : AllocType);
3200 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3200, __PRETTY_FUNCTION__))
;
3201 QualType CharType = CAT->getElementType();
3202 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3202, __PRETTY_FUNCTION__))
;
3203
3204 unsigned Elts = CAT->getSize().getZExtValue();
3205 Result = APValue(APValue::UninitArray(),
3206 std::min(S->getLength(), Elts), Elts);
3207 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3208 CharType->isUnsignedIntegerType());
3209 if (Result.hasArrayFiller())
3210 Result.getArrayFiller() = APValue(Value);
3211 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3212 Value = S->getCodeUnit(I);
3213 Result.getArrayInitializedElt(I) = APValue(Value);
3214 }
3215}
3216
3217// Expand an array so that it has more than Index filled elements.
3218static void expandArray(APValue &Array, unsigned Index) {
3219 unsigned Size = Array.getArraySize();
3220 assert(Index < Size)((Index < Size) ? static_cast<void> (0) : __assert_fail
("Index < Size", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3220, __PRETTY_FUNCTION__))
;
3221
3222 // Always at least double the number of elements for which we store a value.
3223 unsigned OldElts = Array.getArrayInitializedElts();
3224 unsigned NewElts = std::max(Index+1, OldElts * 2);
3225 NewElts = std::min(Size, std::max(NewElts, 8u));
3226
3227 // Copy the data across.
3228 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3229 for (unsigned I = 0; I != OldElts; ++I)
3230 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3231 for (unsigned I = OldElts; I != NewElts; ++I)
3232 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3233 if (NewValue.hasArrayFiller())
3234 NewValue.getArrayFiller() = Array.getArrayFiller();
3235 Array.swap(NewValue);
3236}
3237
3238/// Determine whether a type would actually be read by an lvalue-to-rvalue
3239/// conversion. If it's of class type, we may assume that the copy operation
3240/// is trivial. Note that this is never true for a union type with fields
3241/// (because the copy always "reads" the active member) and always true for
3242/// a non-class type.
3243static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3244static bool isReadByLvalueToRvalueConversion(QualType T) {
3245 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3246 return !RD || isReadByLvalueToRvalueConversion(RD);
3247}
3248static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3249 // FIXME: A trivial copy of a union copies the object representation, even if
3250 // the union is empty.
3251 if (RD->isUnion())
3252 return !RD->field_empty();
3253 if (RD->isEmpty())
3254 return false;
3255
3256 for (auto *Field : RD->fields())
3257 if (!Field->isUnnamedBitfield() &&
3258 isReadByLvalueToRvalueConversion(Field->getType()))
3259 return true;
3260
3261 for (auto &BaseSpec : RD->bases())
3262 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3263 return true;
3264
3265 return false;
3266}
3267
3268/// Diagnose an attempt to read from any unreadable field within the specified
3269/// type, which might be a class type.
3270static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3271 QualType T) {
3272 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3273 if (!RD)
3274 return false;
3275
3276 if (!RD->hasMutableFields())
3277 return false;
3278
3279 for (auto *Field : RD->fields()) {
3280 // If we're actually going to read this field in some way, then it can't
3281 // be mutable. If we're in a union, then assigning to a mutable field
3282 // (even an empty one) can change the active member, so that's not OK.
3283 // FIXME: Add core issue number for the union case.
3284 if (Field->isMutable() &&
3285 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3286 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3287 Info.Note(Field->getLocation(), diag::note_declared_at);
3288 return true;
3289 }
3290
3291 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3292 return true;
3293 }
3294
3295 for (auto &BaseSpec : RD->bases())
3296 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3297 return true;
3298
3299 // All mutable fields were empty, and thus not actually read.
3300 return false;
3301}
3302
3303static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3304 APValue::LValueBase Base,
3305 bool MutableSubobject = false) {
3306 // A temporary we created.
3307 if (Base.getCallIndex())
3308 return true;
3309
3310 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3311 if (!Evaluating)
3312 return false;
3313
3314 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3315
3316 switch (Info.IsEvaluatingDecl) {
3317 case EvalInfo::EvaluatingDeclKind::None:
3318 return false;
3319
3320 case EvalInfo::EvaluatingDeclKind::Ctor:
3321 // The variable whose initializer we're evaluating.
3322 if (BaseD)
3323 return declaresSameEntity(Evaluating, BaseD);
3324
3325 // A temporary lifetime-extended by the variable whose initializer we're
3326 // evaluating.
3327 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3328 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3329 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3330 return false;
3331
3332 case EvalInfo::EvaluatingDeclKind::Dtor:
3333 // C++2a [expr.const]p6:
3334 // [during constant destruction] the lifetime of a and its non-mutable
3335 // subobjects (but not its mutable subobjects) [are] considered to start
3336 // within e.
3337 //
3338 // FIXME: We can meaningfully extend this to cover non-const objects, but
3339 // we will need special handling: we should be able to access only
3340 // subobjects of such objects that are themselves declared const.
3341 if (!BaseD ||
3342 !(BaseD->getType().isConstQualified() ||
3343 BaseD->getType()->isReferenceType()) ||
3344 MutableSubobject)
3345 return false;
3346 return declaresSameEntity(Evaluating, BaseD);
3347 }
3348
3349 llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3349)
;
3350}
3351
3352namespace {
3353/// A handle to a complete object (an object that is not a subobject of
3354/// another object).
3355struct CompleteObject {
3356 /// The identity of the object.
3357 APValue::LValueBase Base;
3358 /// The value of the complete object.
3359 APValue *Value;
3360 /// The type of the complete object.
3361 QualType Type;
3362
3363 CompleteObject() : Value(nullptr) {}
3364 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3365 : Base(Base), Value(Value), Type(Type) {}
3366
3367 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3368 // If this isn't a "real" access (eg, if it's just accessing the type
3369 // info), allow it. We assume the type doesn't change dynamically for
3370 // subobjects of constexpr objects (even though we'd hit UB here if it
3371 // did). FIXME: Is this right?
3372 if (!isAnyAccess(AK))
3373 return true;
3374
3375 // In C++14 onwards, it is permitted to read a mutable member whose
3376 // lifetime began within the evaluation.
3377 // FIXME: Should we also allow this in C++11?
3378 if (!Info.getLangOpts().CPlusPlus14)
3379 return false;
3380 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3381 }
3382
3383 explicit operator bool() const { return !Type.isNull(); }
3384};
3385} // end anonymous namespace
3386
3387static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3388 bool IsMutable = false) {
3389 // C++ [basic.type.qualifier]p1:
3390 // - A const object is an object of type const T or a non-mutable subobject
3391 // of a const object.
3392 if (ObjType.isConstQualified() && !IsMutable)
3393 SubobjType.addConst();
3394 // - A volatile object is an object of type const T or a subobject of a
3395 // volatile object.
3396 if (ObjType.isVolatileQualified())
3397 SubobjType.addVolatile();
3398 return SubobjType;
3399}
3400
3401/// Find the designated sub-object of an rvalue.
3402template<typename SubobjectHandler>
3403typename SubobjectHandler::result_type
3404findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3405 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3406 if (Sub.Invalid)
3407 // A diagnostic will have already been produced.
3408 return handler.failed();
3409 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3410 if (Info.getLangOpts().CPlusPlus11)
3411 Info.FFDiag(E, Sub.isOnePastTheEnd()
3412 ? diag::note_constexpr_access_past_end
3413 : diag::note_constexpr_access_unsized_array)
3414 << handler.AccessKind;
3415 else
3416 Info.FFDiag(E);
3417 return handler.failed();
3418 }
3419
3420 APValue *O = Obj.Value;
3421 QualType ObjType = Obj.Type;
3422 const FieldDecl *LastField = nullptr;
3423 const FieldDecl *VolatileField = nullptr;
3424
3425 // Walk the designator's path to find the subobject.
3426 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3427 // Reading an indeterminate value is undefined, but assigning over one is OK.
3428 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3429 (O->isIndeterminate() &&
3430 !isValidIndeterminateAccess(handler.AccessKind))) {
3431 if (!Info.checkingPotentialConstantExpression())
3432 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3433 << handler.AccessKind << O->isIndeterminate();
3434 return handler.failed();
3435 }
3436
3437 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3438 // const and volatile semantics are not applied on an object under
3439 // {con,de}struction.
3440 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3441 ObjType->isRecordType() &&
3442 Info.isEvaluatingCtorDtor(
3443 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3444 Sub.Entries.begin() + I)) !=
3445 ConstructionPhase::None) {
3446 ObjType = Info.Ctx.getCanonicalType(ObjType);
3447 ObjType.removeLocalConst();
3448 ObjType.removeLocalVolatile();
3449 }
3450
3451 // If this is our last pass, check that the final object type is OK.
3452 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3453 // Accesses to volatile objects are prohibited.
3454 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3455 if (Info.getLangOpts().CPlusPlus) {
3456 int DiagKind;
3457 SourceLocation Loc;
3458 const NamedDecl *Decl = nullptr;
3459 if (VolatileField) {
3460 DiagKind = 2;
3461 Loc = VolatileField->getLocation();
3462 Decl = VolatileField;
3463 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3464 DiagKind = 1;
3465 Loc = VD->getLocation();
3466 Decl = VD;
3467 } else {
3468 DiagKind = 0;
3469 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3470 Loc = E->getExprLoc();
3471 }
3472 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3473 << handler.AccessKind << DiagKind << Decl;
3474 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3475 } else {
3476 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3477 }
3478 return handler.failed();
3479 }
3480
3481 // If we are reading an object of class type, there may still be more
3482 // things we need to check: if there are any mutable subobjects, we
3483 // cannot perform this read. (This only happens when performing a trivial
3484 // copy or assignment.)
3485 if (ObjType->isRecordType() &&
3486 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3487 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3488 return handler.failed();
3489 }
3490
3491 if (I == N) {
3492 if (!handler.found(*O, ObjType))
3493 return false;
3494
3495 // If we modified a bit-field, truncate it to the right width.
3496 if (isModification(handler.AccessKind) &&
3497 LastField && LastField->isBitField() &&
3498 !truncateBitfieldValue(Info, E, *O, LastField))
3499 return false;
3500
3501 return true;
3502 }
3503
3504 LastField = nullptr;
3505 if (ObjType->isArrayType()) {
3506 // Next subobject is an array element.
3507 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3508 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3508, __PRETTY_FUNCTION__))
;
3509 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3510 if (CAT->getSize().ule(Index)) {
3511 // Note, it should not be possible to form a pointer with a valid
3512 // designator which points more than one past the end of the array.
3513 if (Info.getLangOpts().CPlusPlus11)
3514 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3515 << handler.AccessKind;
3516 else
3517 Info.FFDiag(E);
3518 return handler.failed();
3519 }
3520
3521 ObjType = CAT->getElementType();
3522
3523 if (O->getArrayInitializedElts() > Index)
3524 O = &O->getArrayInitializedElt(Index);
3525 else if (!isRead(handler.AccessKind)) {
3526 expandArray(*O, Index);
3527 O = &O->getArrayInitializedElt(Index);
3528 } else
3529 O = &O->getArrayFiller();
3530 } else if (ObjType->isAnyComplexType()) {
3531 // Next subobject is a complex number.
3532 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3533 if (Index > 1) {
3534 if (Info.getLangOpts().CPlusPlus11)
3535 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3536 << handler.AccessKind;
3537 else
3538 Info.FFDiag(E);
3539 return handler.failed();
3540 }
3541
3542 ObjType = getSubobjectType(
3543 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3544
3545 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3545, __PRETTY_FUNCTION__))
;
3546 if (O->isComplexInt()) {
3547 return handler.found(Index ? O->getComplexIntImag()
3548 : O->getComplexIntReal(), ObjType);
3549 } else {
3550 assert(O->isComplexFloat())((O->isComplexFloat()) ? static_cast<void> (0) : __assert_fail
("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3550, __PRETTY_FUNCTION__))
;
3551 return handler.found(Index ? O->getComplexFloatImag()
3552 : O->getComplexFloatReal(), ObjType);
3553 }
3554 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3555 if (Field->isMutable() &&
3556 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3557 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3558 << handler.AccessKind << Field;
3559 Info.Note(Field->getLocation(), diag::note_declared_at);
3560 return handler.failed();
3561 }
3562
3563 // Next subobject is a class, struct or union field.
3564 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3565 if (RD->isUnion()) {
3566 const FieldDecl *UnionField = O->getUnionField();
3567 if (!UnionField ||
3568 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3569 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3570 // Placement new onto an inactive union member makes it active.
3571 O->setUnion(Field, APValue());
3572 } else {
3573 // FIXME: If O->getUnionValue() is absent, report that there's no
3574 // active union member rather than reporting the prior active union
3575 // member. We'll need to fix nullptr_t to not use APValue() as its
3576 // representation first.
3577 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3578 << handler.AccessKind << Field << !UnionField << UnionField;
3579 return handler.failed();
3580 }
3581 }
3582 O = &O->getUnionValue();
3583 } else
3584 O = &O->getStructField(Field->getFieldIndex());
3585
3586 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3587 LastField = Field;
3588 if (Field->getType().isVolatileQualified())
3589 VolatileField = Field;
3590 } else {
3591 // Next subobject is a base class.
3592 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3593 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3594 O = &O->getStructBase(getBaseIndex(Derived, Base));
3595
3596 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3597 }
3598 }
3599}
3600
3601namespace {
3602struct ExtractSubobjectHandler {
3603 EvalInfo &Info;
3604 const Expr *E;
3605 APValue &Result;
3606 const AccessKinds AccessKind;
3607
3608 typedef bool result_type;
3609 bool failed() { return false; }
3610 bool found(APValue &Subobj, QualType SubobjType) {
3611 Result = Subobj;
3612 if (AccessKind == AK_ReadObjectRepresentation)
3613 return true;
3614 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3615 }
3616 bool found(APSInt &Value, QualType SubobjType) {
3617 Result = APValue(Value);
3618 return true;
3619 }
3620 bool found(APFloat &Value, QualType SubobjType) {
3621 Result = APValue(Value);
3622 return true;
3623 }
3624};
3625} // end anonymous namespace
3626
3627/// Extract the designated sub-object of an rvalue.
3628static bool extractSubobject(EvalInfo &Info, const Expr *E,
3629 const CompleteObject &Obj,
3630 const SubobjectDesignator &Sub, APValue &Result,
3631 AccessKinds AK = AK_Read) {
3632 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3632, __PRETTY_FUNCTION__))
;
3633 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3634 return findSubobject(Info, E, Obj, Sub, Handler);
3635}
3636
3637namespace {
3638struct ModifySubobjectHandler {
3639 EvalInfo &Info;
3640 APValue &NewVal;
3641 const Expr *E;
3642
3643 typedef bool result_type;
3644 static const AccessKinds AccessKind = AK_Assign;
3645
3646 bool checkConst(QualType QT) {
3647 // Assigning to a const object has undefined behavior.
3648 if (QT.isConstQualified()) {
3649 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3650 return false;
3651 }
3652 return true;
3653 }
3654
3655 bool failed() { return false; }
3656 bool found(APValue &Subobj, QualType SubobjType) {
3657 if (!checkConst(SubobjType))
3658 return false;
3659 // We've been given ownership of NewVal, so just swap it in.
3660 Subobj.swap(NewVal);
3661 return true;
3662 }
3663 bool found(APSInt &Value, QualType SubobjType) {
3664 if (!checkConst(SubobjType))
3665 return false;
3666 if (!NewVal.isInt()) {
3667 // Maybe trying to write a cast pointer value into a complex?
3668 Info.FFDiag(E);
3669 return false;
3670 }
3671 Value = NewVal.getInt();
3672 return true;
3673 }
3674 bool found(APFloat &Value, QualType SubobjType) {
3675 if (!checkConst(SubobjType))
3676 return false;
3677 Value = NewVal.getFloat();
3678 return true;
3679 }
3680};
3681} // end anonymous namespace
3682
3683const AccessKinds ModifySubobjectHandler::AccessKind;
3684
3685/// Update the designated sub-object of an rvalue to the given value.
3686static bool modifySubobject(EvalInfo &Info, const Expr *E,
3687 const CompleteObject &Obj,
3688 const SubobjectDesignator &Sub,
3689 APValue &NewVal) {
3690 ModifySubobjectHandler Handler = { Info, NewVal, E };
3691 return findSubobject(Info, E, Obj, Sub, Handler);
3692}
3693
3694/// Find the position where two subobject designators diverge, or equivalently
3695/// the length of the common initial subsequence.
3696static unsigned FindDesignatorMismatch(QualType ObjType,
3697 const SubobjectDesignator &A,
3698 const SubobjectDesignator &B,
3699 bool &WasArrayIndex) {
3700 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3701 for (/**/; I != N; ++I) {
3702 if (!ObjType.isNull() &&
3703 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3704 // Next subobject is an array element.
3705 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3706 WasArrayIndex = true;
3707 return I;
3708 }
3709 if (ObjType->isAnyComplexType())
3710 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3711 else
3712 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3713 } else {
3714 if (A.Entries[I].getAsBaseOrMember() !=
3715 B.Entries[I].getAsBaseOrMember()) {
3716 WasArrayIndex = false;
3717 return I;
3718 }
3719 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3720 // Next subobject is a field.
3721 ObjType = FD->getType();
3722 else
3723 // Next subobject is a base class.
3724 ObjType = QualType();
3725 }
3726 }
3727 WasArrayIndex = false;
3728 return I;
3729}
3730
3731/// Determine whether the given subobject designators refer to elements of the
3732/// same array object.
3733static bool AreElementsOfSameArray(QualType ObjType,
3734 const SubobjectDesignator &A,
3735 const SubobjectDesignator &B) {
3736 if (A.Entries.size() != B.Entries.size())
3737 return false;
3738
3739 bool IsArray = A.MostDerivedIsArrayElement;
3740 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3741 // A is a subobject of the array element.
3742 return false;
3743
3744 // If A (and B) designates an array element, the last entry will be the array
3745 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3746 // of length 1' case, and the entire path must match.
3747 bool WasArrayIndex;
3748 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3749 return CommonLength >= A.Entries.size() - IsArray;
3750}
3751
3752/// Find the complete object to which an LValue refers.
3753static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3754 AccessKinds AK, const LValue &LVal,
3755 QualType LValType) {
3756 if (LVal.InvalidBase) {
3757 Info.FFDiag(E);
3758 return CompleteObject();
3759 }
3760
3761 if (!LVal.Base) {
3762 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3763 return CompleteObject();
3764 }
3765
3766 CallStackFrame *Frame = nullptr;
3767 unsigned Depth = 0;
3768 if (LVal.getLValueCallIndex()) {
3769 std::tie(Frame, Depth) =
3770 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3771 if (!Frame) {
3772 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3773 << AK << LVal.Base.is<const ValueDecl*>();
3774 NoteLValueLocation(Info, LVal.Base);
3775 return CompleteObject();
3776 }
3777 }
3778
3779 bool IsAccess = isAnyAccess(AK);
3780
3781 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3782 // is not a constant expression (even if the object is non-volatile). We also
3783 // apply this rule to C++98, in order to conform to the expected 'volatile'
3784 // semantics.
3785 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3786 if (Info.getLangOpts().CPlusPlus)
3787 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3788 << AK << LValType;
3789 else
3790 Info.FFDiag(E);
3791 return CompleteObject();
3792 }
3793
3794 // Compute value storage location and type of base object.
3795 APValue *BaseVal = nullptr;
3796 QualType BaseType = getType(LVal.Base);
3797
3798 if (const ConstantExpr *CE =
3799 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3800 /// Nested immediate invocation have been previously removed so if we found
3801 /// a ConstantExpr it can only be the EvaluatingDecl.
3802 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3802, __PRETTY_FUNCTION__))
;
3803 (void)CE;
3804 BaseVal = Info.EvaluatingDeclValue;
3805 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3806 // Allow reading from a GUID declaration.
3807 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3808 if (isModification(AK)) {
3809 // All the remaining cases do not permit modification of the object.
3810 Info.FFDiag(E, diag::note_constexpr_modify_global);
3811 return CompleteObject();
3812 }
3813 APValue &V = GD->getAsAPValue();
3814 if (V.isAbsent()) {
3815 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3816 << GD->getType();
3817 return CompleteObject();
3818 }
3819 return CompleteObject(LVal.Base, &V, GD->getType());
3820 }
3821
3822 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3823 // In C++11, constexpr, non-volatile variables initialized with constant
3824 // expressions are constant expressions too. Inside constexpr functions,
3825 // parameters are constant expressions even if they're non-const.
3826 // In C++1y, objects local to a constant expression (those with a Frame) are
3827 // both readable and writable inside constant expressions.
3828 // In C, such things can also be folded, although they are not ICEs.
3829 const VarDecl *VD = dyn_cast<VarDecl>(D);
3830 if (VD) {
3831 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3832 VD = VDef;
3833 }
3834 if (!VD || VD->isInvalidDecl()) {
3835 Info.FFDiag(E);
3836 return CompleteObject();
3837 }
3838
3839 // In OpenCL if a variable is in constant address space it is a const value.
3840 bool IsConstant = BaseType.isConstQualified() ||
3841 (Info.getLangOpts().OpenCL &&
3842 BaseType.getAddressSpace() == LangAS::opencl_constant);
3843
3844 // Unless we're looking at a local variable or argument in a constexpr call,
3845 // the variable we're reading must be const.
3846 if (!Frame) {
3847 if (Info.getLangOpts().CPlusPlus14 &&
3848 lifetimeStartedInEvaluation(Info, LVal.Base)) {
3849 // OK, we can read and modify an object if we're in the process of
3850 // evaluating its initializer, because its lifetime began in this
3851 // evaluation.
3852 } else if (isModification(AK)) {
3853 // All the remaining cases do not permit modification of the object.
3854 Info.FFDiag(E, diag::note_constexpr_modify_global);
3855 return CompleteObject();
3856 } else if (VD->isConstexpr()) {
3857 // OK, we can read this variable.
3858 } else if (BaseType->isIntegralOrEnumerationType()) {
3859 // In OpenCL if a variable is in constant address space it is a const
3860 // value.
3861 if (!IsConstant) {
3862 if (!IsAccess)
3863 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3864 if (Info.getLangOpts().CPlusPlus) {
3865 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3866 Info.Note(VD->getLocation(), diag::note_declared_at);
3867 } else {
3868 Info.FFDiag(E);
3869 }
3870 return CompleteObject();
3871 }
3872 } else if (!IsAccess) {
3873 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3874 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
3875 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
3876 // This variable might end up being constexpr. Don't diagnose it yet.
3877 } else if (IsConstant) {
3878 // Keep evaluating to see what we can do. In particular, we support
3879 // folding of const floating-point types, in order to make static const
3880 // data members of such types (supported as an extension) more useful.
3881 if (Info.getLangOpts().CPlusPlus) {
3882 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
3883 ? diag::note_constexpr_ltor_non_constexpr
3884 : diag::note_constexpr_ltor_non_integral, 1)
3885 << VD << BaseType;
3886 Info.Note(VD->getLocation(), diag::note_declared_at);
3887 } else {
3888 Info.CCEDiag(E);
3889 }
3890 } else {
3891 // Never allow reading a non-const value.
3892 if (Info.getLangOpts().CPlusPlus) {
3893 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3894 ? diag::note_constexpr_ltor_non_constexpr
3895 : diag::note_constexpr_ltor_non_integral, 1)
3896 << VD << BaseType;
3897 Info.Note(VD->getLocation(), diag::note_declared_at);
3898 } else {
3899 Info.FFDiag(E);
3900 }
3901 return CompleteObject();
3902 }
3903 }
3904
3905 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3906 return CompleteObject();
3907 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3908 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3909 if (!Alloc) {
3910 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3911 return CompleteObject();
3912 }
3913 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3914 LVal.Base.getDynamicAllocType());
3915 } else {
3916 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3917
3918 if (!Frame) {
3919 if (const MaterializeTemporaryExpr *MTE =
3920 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3921 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3922, __PRETTY_FUNCTION__))
3922 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3922, __PRETTY_FUNCTION__))
;
3923
3924 // Per C++1y [expr.const]p2:
3925 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3926 // - a [...] glvalue of integral or enumeration type that refers to
3927 // a non-volatile const object [...]
3928 // [...]
3929 // - a [...] glvalue of literal type that refers to a non-volatile
3930 // object whose lifetime began within the evaluation of e.
3931 //
3932 // C++11 misses the 'began within the evaluation of e' check and
3933 // instead allows all temporaries, including things like:
3934 // int &&r = 1;
3935 // int x = ++r;
3936 // constexpr int k = r;
3937 // Therefore we use the C++14 rules in C++11 too.
3938 //
3939 // Note that temporaries whose lifetimes began while evaluating a
3940 // variable's constructor are not usable while evaluating the
3941 // corresponding destructor, not even if they're of const-qualified
3942 // types.
3943 if (!(BaseType.isConstQualified() &&
3944 BaseType->isIntegralOrEnumerationType()) &&
3945 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3946 if (!IsAccess)
3947 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3948 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3949 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3950 return CompleteObject();
3951 }
3952
3953 BaseVal = MTE->getOrCreateValue(false);
3954 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3954, __PRETTY_FUNCTION__))
;
3955 } else {
3956 if (!IsAccess)
3957 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3958 APValue Val;
3959 LVal.moveInto(Val);
3960 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3961 << AK
3962 << Val.getAsString(Info.Ctx,
3963 Info.Ctx.getLValueReferenceType(LValType));
3964 NoteLValueLocation(Info, LVal.Base);
3965 return CompleteObject();
3966 }
3967 } else {
3968 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3969 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 3969, __PRETTY_FUNCTION__))
;
3970 }
3971 }
3972
3973 // In C++14, we can't safely access any mutable state when we might be
3974 // evaluating after an unmodeled side effect.
3975 //
3976 // FIXME: Not all local state is mutable. Allow local constant subobjects
3977 // to be read here (but take care with 'mutable' fields).
3978 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3979 Info.EvalStatus.HasSideEffects) ||
3980 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3981 return CompleteObject();
3982
3983 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3984}
3985
3986/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3987/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3988/// glvalue referred to by an entity of reference type.
3989///
3990/// \param Info - Information about the ongoing evaluation.
3991/// \param Conv - The expression for which we are performing the conversion.
3992/// Used for diagnostics.
3993/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3994/// case of a non-class type).
3995/// \param LVal - The glvalue on which we are attempting to perform this action.
3996/// \param RVal - The produced value will be placed here.
3997/// \param WantObjectRepresentation - If true, we're looking for the object
3998/// representation rather than the value, and in particular,
3999/// there is no requirement that the result be fully initialized.
4000static bool
4001handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4002 const LValue &LVal, APValue &RVal,
4003 bool WantObjectRepresentation = false) {
4004 if (LVal.Designator.Invalid)
4005 return false;
4006
4007 // Check for special cases where there is no existing APValue to look at.
4008 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4009
4010 AccessKinds AK =
4011 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4012
4013 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4014 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4015 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4016 // initializer until now for such expressions. Such an expression can't be
4017 // an ICE in C, so this only matters for fold.
4018 if (Type.isVolatileQualified()) {
4019 Info.FFDiag(Conv);
4020 return false;
4021 }
4022 APValue Lit;
4023 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4024 return false;
4025 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4026 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4027 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4028 // Special-case character extraction so we don't have to construct an
4029 // APValue for the whole string.
4030 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4031, __PRETTY_FUNCTION__))
4031 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4031, __PRETTY_FUNCTION__))
;
4032 if (LVal.Designator.Entries.empty()) {
4033 // Fail for now for LValue to RValue conversion of an array.
4034 // (This shouldn't show up in C/C++, but it could be triggered by a
4035 // weird EvaluateAsRValue call from a tool.)
4036 Info.FFDiag(Conv);
4037 return false;
4038 }
4039 if (LVal.Designator.isOnePastTheEnd()) {
4040 if (Info.getLangOpts().CPlusPlus11)
4041 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4042 else
4043 Info.FFDiag(Conv);
4044 return false;
4045 }
4046 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4047 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4048 return true;
4049 }
4050 }
4051
4052 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4053 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4054}
4055
4056/// Perform an assignment of Val to LVal. Takes ownership of Val.
4057static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4058 QualType LValType, APValue &Val) {
4059 if (LVal.Designator.Invalid)
4060 return false;
4061
4062 if (!Info.getLangOpts().CPlusPlus14) {
4063 Info.FFDiag(E);
4064 return false;
4065 }
4066
4067 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4068 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4069}
4070
4071namespace {
4072struct CompoundAssignSubobjectHandler {
4073 EvalInfo &Info;
4074 const Expr *E;
4075 QualType PromotedLHSType;
4076 BinaryOperatorKind Opcode;
4077 const APValue &RHS;
4078
4079 static const AccessKinds AccessKind = AK_Assign;
4080
4081 typedef bool result_type;
4082
4083 bool checkConst(QualType QT) {
4084 // Assigning to a const object has undefined behavior.
4085 if (QT.isConstQualified()) {
4086 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4087 return false;
4088 }
4089 return true;
4090 }
4091
4092 bool failed() { return false; }
4093 bool found(APValue &Subobj, QualType SubobjType) {
4094 switch (Subobj.getKind()) {
4095 case APValue::Int:
4096 return found(Subobj.getInt(), SubobjType);
4097 case APValue::Float:
4098 return found(Subobj.getFloat(), SubobjType);
4099 case APValue::ComplexInt:
4100 case APValue::ComplexFloat:
4101 // FIXME: Implement complex compound assignment.
4102 Info.FFDiag(E);
4103 return false;
4104 case APValue::LValue:
4105 return foundPointer(Subobj, SubobjType);
4106 case APValue::Vector:
4107 return foundVector(Subobj, SubobjType);
4108 default:
4109 // FIXME: can this happen?
4110 Info.FFDiag(E);
4111 return false;
4112 }
4113 }
4114
4115 bool foundVector(APValue &Value, QualType SubobjType) {
4116 if (!checkConst(SubobjType))
4117 return false;
4118
4119 if (!SubobjType->isVectorType()) {
4120 Info.FFDiag(E);
4121 return false;
4122 }
4123 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4124 }
4125
4126 bool found(APSInt &Value, QualType SubobjType) {
4127 if (!checkConst(SubobjType))
4128 return false;
4129
4130 if (!SubobjType->isIntegerType()) {
4131 // We don't support compound assignment on integer-cast-to-pointer
4132 // values.
4133 Info.FFDiag(E);
4134 return false;
4135 }
4136
4137 if (RHS.isInt()) {
4138 APSInt LHS =
4139 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4140 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4141 return false;
4142 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4143 return true;
4144 } else if (RHS.isFloat()) {
4145 APFloat FValue(0.0);
4146 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4147 FValue) &&
4148 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4149 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4150 Value);
4151 }
4152
4153 Info.FFDiag(E);
4154 return false;
4155 }
4156 bool found(APFloat &Value, QualType SubobjType) {
4157 return checkConst(SubobjType) &&
4158 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4159 Value) &&
4160 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4161 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4162 }
4163 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4164 if (!checkConst(SubobjType))
4165 return false;
4166
4167 QualType PointeeType;
4168 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4169 PointeeType = PT->getPointeeType();
4170
4171 if (PointeeType.isNull() || !RHS.isInt() ||
4172 (Opcode != BO_Add && Opcode != BO_Sub)) {
4173 Info.FFDiag(E);
4174 return false;
4175 }
4176
4177 APSInt Offset = RHS.getInt();
4178 if (Opcode == BO_Sub)
4179 negateAsSigned(Offset);
4180
4181 LValue LVal;
4182 LVal.setFrom(Info.Ctx, Subobj);
4183 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4184 return false;
4185 LVal.moveInto(Subobj);
4186 return true;
4187 }
4188};
4189} // end anonymous namespace
4190
4191const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4192
4193/// Perform a compound assignment of LVal <op>= RVal.
4194static bool handleCompoundAssignment(
4195 EvalInfo &Info, const Expr *E,
4196 const LValue &LVal, QualType LValType, QualType PromotedLValType,
4197 BinaryOperatorKind Opcode, const APValue &RVal) {
4198 if (LVal.Designator.Invalid)
4199 return false;
4200
4201 if (!Info.getLangOpts().CPlusPlus14) {
4202 Info.FFDiag(E);
4203 return false;
4204 }
4205
4206 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4207 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4208 RVal };
4209 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4210}
4211
4212namespace {
4213struct IncDecSubobjectHandler {
4214 EvalInfo &Info;
4215 const UnaryOperator *E;
4216 AccessKinds AccessKind;
4217 APValue *Old;
4218
4219 typedef bool result_type;
4220
4221 bool checkConst(QualType QT) {
4222 // Assigning to a const object has undefined behavior.
4223 if (QT.isConstQualified()) {
4224 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4225 return false;
4226 }
4227 return true;
4228 }
4229
4230 bool failed() { return false; }
4231 bool found(APValue &Subobj, QualType SubobjType) {
4232 // Stash the old value. Also clear Old, so we don't clobber it later
4233 // if we're post-incrementing a complex.
4234 if (Old) {
4235 *Old = Subobj;
4236 Old = nullptr;
4237 }
4238
4239 switch (Subobj.getKind()) {
4240 case APValue::Int:
4241 return found(Subobj.getInt(), SubobjType);
4242 case APValue::Float:
4243 return found(Subobj.getFloat(), SubobjType);
4244 case APValue::ComplexInt:
4245 return found(Subobj.getComplexIntReal(),
4246 SubobjType->castAs<ComplexType>()->getElementType()
4247 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4248 case APValue::ComplexFloat:
4249 return found(Subobj.getComplexFloatReal(),
4250 SubobjType->castAs<ComplexType>()->getElementType()
4251 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4252 case APValue::LValue:
4253 return foundPointer(Subobj, SubobjType);
4254 default:
4255 // FIXME: can this happen?
4256 Info.FFDiag(E);
4257 return false;
4258 }
4259 }
4260 bool found(APSInt &Value, QualType SubobjType) {
4261 if (!checkConst(SubobjType))
4262 return false;
4263
4264 if (!SubobjType->isIntegerType()) {
4265 // We don't support increment / decrement on integer-cast-to-pointer
4266 // values.
4267 Info.FFDiag(E);
4268 return false;
4269 }
4270
4271 if (Old) *Old = APValue(Value);
4272
4273 // bool arithmetic promotes to int, and the conversion back to bool
4274 // doesn't reduce mod 2^n, so special-case it.
4275 if (SubobjType->isBooleanType()) {
4276 if (AccessKind == AK_Increment)
4277 Value = 1;
4278 else
4279 Value = !Value;
4280 return true;
4281 }
4282
4283 bool WasNegative = Value.isNegative();
4284 if (AccessKind == AK_Increment) {
4285 ++Value;
4286
4287 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4288 APSInt ActualValue(Value, /*IsUnsigned*/true);
4289 return HandleOverflow(Info, E, ActualValue, SubobjType);
4290 }
4291 } else {
4292 --Value;
4293
4294 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4295 unsigned BitWidth = Value.getBitWidth();
4296 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4297 ActualValue.setBit(BitWidth);
4298 return HandleOverflow(Info, E, ActualValue, SubobjType);
4299 }
4300 }
4301 return true;
4302 }
4303 bool found(APFloat &Value, QualType SubobjType) {
4304 if (!checkConst(SubobjType))
4305 return false;
4306
4307 if (Old) *Old = APValue(Value);
4308
4309 APFloat One(Value.getSemantics(), 1);
4310 if (AccessKind == AK_Increment)
4311 Value.add(One, APFloat::rmNearestTiesToEven);
4312 else
4313 Value.subtract(One, APFloat::rmNearestTiesToEven);
4314 return true;
4315 }
4316 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4317 if (!checkConst(SubobjType))
4318 return false;
4319
4320 QualType PointeeType;
4321 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4322 PointeeType = PT->getPointeeType();
4323 else {
4324 Info.FFDiag(E);
4325 return false;
4326 }
4327
4328 LValue LVal;
4329 LVal.setFrom(Info.Ctx, Subobj);
4330 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4331 AccessKind == AK_Increment ? 1 : -1))
4332 return false;
4333 LVal.moveInto(Subobj);
4334 return true;
4335 }
4336};
4337} // end anonymous namespace
4338
4339/// Perform an increment or decrement on LVal.
4340static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4341 QualType LValType, bool IsIncrement, APValue *Old) {
4342 if (LVal.Designator.Invalid)
4343 return false;
4344
4345 if (!Info.getLangOpts().CPlusPlus14) {
4346 Info.FFDiag(E);
4347 return false;
4348 }
4349
4350 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4351 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4352 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4353 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4354}
4355
4356/// Build an lvalue for the object argument of a member function call.
4357static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4358 LValue &This) {
4359 if (Object->getType()->isPointerType() && Object->isRValue())
4360 return EvaluatePointer(Object, This, Info);
4361
4362 if (Object->isGLValue())
4363 return EvaluateLValue(Object, This, Info);
4364
4365 if (Object->getType()->isLiteralType(Info.Ctx))
4366 return EvaluateTemporary(Object, This, Info);
4367
4368 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4369 return false;
4370}
4371
4372/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4373/// lvalue referring to the result.
4374///
4375/// \param Info - Information about the ongoing evaluation.
4376/// \param LV - An lvalue referring to the base of the member pointer.
4377/// \param RHS - The member pointer expression.
4378/// \param IncludeMember - Specifies whether the member itself is included in
4379/// the resulting LValue subobject designator. This is not possible when
4380/// creating a bound member function.
4381/// \return The field or method declaration to which the member pointer refers,
4382/// or 0 if evaluation fails.
4383static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4384 QualType LVType,
4385 LValue &LV,
4386 const Expr *RHS,
4387 bool IncludeMember = true) {
4388 MemberPtr MemPtr;
4389 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4390 return nullptr;
4391
4392 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4393 // member value, the behavior is undefined.
4394 if (!MemPtr.getDecl()) {
4395 // FIXME: Specific diagnostic.
4396 Info.FFDiag(RHS);
4397 return nullptr;
4398 }
4399
4400 if (MemPtr.isDerivedMember()) {
4401 // This is a member of some derived class. Truncate LV appropriately.
4402 // The end of the derived-to-base path for the base object must match the
4403 // derived-to-base path for the member pointer.
4404 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4405 LV.Designator.Entries.size()) {
4406 Info.FFDiag(RHS);
4407 return nullptr;
4408 }
4409 unsigned PathLengthToMember =
4410 LV.Designator.Entries.size() - MemPtr.Path.size();
4411 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4412 const CXXRecordDecl *LVDecl = getAsBaseClass(
4413 LV.Designator.Entries[PathLengthToMember + I]);
4414 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4415 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4416 Info.FFDiag(RHS);
4417 return nullptr;
4418 }
4419 }
4420
4421 // Truncate the lvalue to the appropriate derived class.
4422 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4423 PathLengthToMember))
4424 return nullptr;
4425 } else if (!MemPtr.Path.empty()) {
4426 // Extend the LValue path with the member pointer's path.
4427 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4428 MemPtr.Path.size() + IncludeMember);
4429
4430 // Walk down to the appropriate base class.
4431 if (const PointerType *PT = LVType->getAs<PointerType>())
4432 LVType = PT->getPointeeType();
4433 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4434 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4434, __PRETTY_FUNCTION__))
;
4435 // The first class in the path is that of the lvalue.
4436 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4437 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4438 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4439 return nullptr;
4440 RD = Base;
4441 }
4442 // Finally cast to the class containing the member.
4443 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4444 MemPtr.getContainingRecord()))
4445 return nullptr;
4446 }
4447
4448 // Add the member. Note that we cannot build bound member functions here.
4449 if (IncludeMember) {
4450 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4451 if (!HandleLValueMember(Info, RHS, LV, FD))
4452 return nullptr;
4453 } else if (const IndirectFieldDecl *IFD =
4454 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4455 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4456 return nullptr;
4457 } else {
4458 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4458)
;
4459 }
4460 }
4461
4462 return MemPtr.getDecl();
4463}
4464
4465static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4466 const BinaryOperator *BO,
4467 LValue &LV,
4468 bool IncludeMember = true) {
4469 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4469, __PRETTY_FUNCTION__))
;
4470
4471 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4472 if (Info.noteFailure()) {
4473 MemberPtr MemPtr;
4474 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4475 }
4476 return nullptr;
4477 }
4478
4479 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4480 BO->getRHS(), IncludeMember);
4481}
4482
4483/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4484/// the provided lvalue, which currently refers to the base object.
4485static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4486 LValue &Result) {
4487 SubobjectDesignator &D = Result.Designator;
4488 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4489 return false;
4490
4491 QualType TargetQT = E->getType();
4492 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4493 TargetQT = PT->getPointeeType();
4494
4495 // Check this cast lands within the final derived-to-base subobject path.
4496 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4497 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4498 << D.MostDerivedType << TargetQT;
4499 return false;
4500 }
4501
4502 // Check the type of the final cast. We don't need to check the path,
4503 // since a cast can only be formed if the path is unique.
4504 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4505 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4506 const CXXRecordDecl *FinalType;
4507 if (NewEntriesSize == D.MostDerivedPathLength)
4508 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4509 else
4510 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4511 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4512 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4513 << D.MostDerivedType << TargetQT;
4514 return false;
4515 }
4516
4517 // Truncate the lvalue to the appropriate derived class.
4518 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4519}
4520
4521/// Get the value to use for a default-initialized object of type T.
4522/// Return false if it encounters something invalid.
4523static bool getDefaultInitValue(QualType T, APValue &Result) {
4524 bool Success = true;
4525 if (auto *RD = T->getAsCXXRecordDecl()) {
4526 if (RD->isInvalidDecl()) {
4527 Result = APValue();
4528 return false;
4529 }
4530 if (RD->isUnion()) {
4531 Result = APValue((const FieldDecl *)nullptr);
4532 return true;
4533 }
4534 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4535 std::distance(RD->field_begin(), RD->field_end()));
4536
4537 unsigned Index = 0;
4538 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4539 End = RD->bases_end();
4540 I != End; ++I, ++Index)
4541 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4542
4543 for (const auto *I : RD->fields()) {
4544 if (I->isUnnamedBitfield())
4545 continue;
4546 Success &= getDefaultInitValue(I->getType(),
4547 Result.getStructField(I->getFieldIndex()));
4548 }
4549 return Success;
4550 }
4551
4552 if (auto *AT =
4553 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4554 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4555 if (Result.hasArrayFiller())
4556 Success &=
4557 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4558
4559 return Success;
4560 }
4561
4562 Result = APValue::IndeterminateValue();
4563 return true;
4564}
4565
4566namespace {
4567enum EvalStmtResult {
4568 /// Evaluation failed.
4569 ESR_Failed,
4570 /// Hit a 'return' statement.
4571 ESR_Returned,
4572 /// Evaluation succeeded.
4573 ESR_Succeeded,
4574 /// Hit a 'continue' statement.
4575 ESR_Continue,
4576 /// Hit a 'break' statement.
4577 ESR_Break,
4578 /// Still scanning for 'case' or 'default' statement.
4579 ESR_CaseNotFound
4580};
4581}
4582
4583static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4584 // We don't need to evaluate the initializer for a static local.
4585 if (!VD->hasLocalStorage())
4586 return true;
4587
4588 LValue Result;
4589 APValue &Val =
4590 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4591
4592 const Expr *InitE = VD->getInit();
4593 if (!InitE)
4594 return getDefaultInitValue(VD->getType(), Val);
4595
4596 if (InitE->isValueDependent())
4597 return false;
4598
4599 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4600 // Wipe out any partially-computed value, to allow tracking that this
4601 // evaluation failed.
4602 Val = APValue();
4603 return false;
4604 }
4605
4606 return true;
4607}
4608
4609static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4610 bool OK = true;
4611
4612 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4613 OK &= EvaluateVarDecl(Info, VD);
4614
4615 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4616 for (auto *BD : DD->bindings())
4617 if (auto *VD = BD->getHoldingVar())
4618 OK &= EvaluateDecl(Info, VD);
4619
4620 return OK;
4621}
4622
4623
4624/// Evaluate a condition (either a variable declaration or an expression).
4625static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4626 const Expr *Cond, bool &Result) {
4627 FullExpressionRAII Scope(Info);
4628 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4629 return false;
4630 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4631 return false;
4632 return Scope.destroy();
4633}
4634
4635namespace {
4636/// A location where the result (returned value) of evaluating a
4637/// statement should be stored.
4638struct StmtResult {
4639 /// The APValue that should be filled in with the returned value.
4640 APValue &Value;
4641 /// The location containing the result, if any (used to support RVO).
4642 const LValue *Slot;
4643};
4644
4645struct TempVersionRAII {
4646 CallStackFrame &Frame;
4647
4648 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4649 Frame.pushTempVersion();
4650 }
4651
4652 ~TempVersionRAII() {
4653 Frame.popTempVersion();
4654 }
4655};
4656
4657}
4658
4659static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4660 const Stmt *S,
4661 const SwitchCase *SC = nullptr);
4662
4663/// Evaluate the body of a loop, and translate the result as appropriate.
4664static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4665 const Stmt *Body,
4666 const SwitchCase *Case = nullptr) {
4667 BlockScopeRAII Scope(Info);
4668
4669 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4670 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4671 ESR = ESR_Failed;
4672
4673 switch (ESR) {
4674 case ESR_Break:
4675 return ESR_Succeeded;
4676 case ESR_Succeeded:
4677 case ESR_Continue:
4678 return ESR_Continue;
4679 case ESR_Failed:
4680 case ESR_Returned:
4681 case ESR_CaseNotFound:
4682 return ESR;
4683 }
4684 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4684)
;
4685}
4686
4687/// Evaluate a switch statement.
4688static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4689 const SwitchStmt *SS) {
4690 BlockScopeRAII Scope(Info);
4691
4692 // Evaluate the switch condition.
4693 APSInt Value;
4694 {
4695 if (const Stmt *Init = SS->getInit()) {
4696 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4697 if (ESR != ESR_Succeeded) {
4698 if (ESR != ESR_Failed && !Scope.destroy())
4699 ESR = ESR_Failed;
4700 return ESR;
4701 }
4702 }
4703
4704 FullExpressionRAII CondScope(Info);
4705 if (SS->getConditionVariable() &&
4706 !EvaluateDecl(Info, SS->getConditionVariable()))
4707 return ESR_Failed;
4708 if (!EvaluateInteger(SS->getCond(), Value, Info))
4709 return ESR_Failed;
4710 if (!CondScope.destroy())
4711 return ESR_Failed;
4712 }
4713
4714 // Find the switch case corresponding to the value of the condition.
4715 // FIXME: Cache this lookup.
4716 const SwitchCase *Found = nullptr;
4717 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4718 SC = SC->getNextSwitchCase()) {
4719 if (isa<DefaultStmt>(SC)) {
4720 Found = SC;
4721 continue;
4722 }
4723
4724 const CaseStmt *CS = cast<CaseStmt>(SC);
4725 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4726 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4727 : LHS;
4728 if (LHS <= Value && Value <= RHS) {
4729 Found = SC;
4730 break;
4731 }
4732 }
4733
4734 if (!Found)
4735 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4736
4737 // Search the switch body for the switch case and evaluate it from there.
4738 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4739 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4740 return ESR_Failed;
4741
4742 switch (ESR) {
4743 case ESR_Break:
4744 return ESR_Succeeded;
4745 case ESR_Succeeded:
4746 case ESR_Continue:
4747 case ESR_Failed:
4748 case ESR_Returned:
4749 return ESR;
4750 case ESR_CaseNotFound:
4751 // This can only happen if the switch case is nested within a statement
4752 // expression. We have no intention of supporting that.
4753 Info.FFDiag(Found->getBeginLoc(),
4754 diag::note_constexpr_stmt_expr_unsupported);
4755 return ESR_Failed;
4756 }
4757 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4757)
;
4758}
4759
4760// Evaluate a statement.
4761static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4762 const Stmt *S, const SwitchCase *Case) {
4763 if (!Info.nextStep(S))
4764 return ESR_Failed;
4765
4766 // If we're hunting down a 'case' or 'default' label, recurse through
4767 // substatements until we hit the label.
4768 if (Case) {
4769 switch (S->getStmtClass()) {
4770 case Stmt::CompoundStmtClass:
4771 // FIXME: Precompute which substatement of a compound statement we
4772 // would jump to, and go straight there rather than performing a
4773 // linear scan each time.
4774 case Stmt::LabelStmtClass:
4775 case Stmt::AttributedStmtClass:
4776 case Stmt::DoStmtClass:
4777 break;
4778
4779 case Stmt::CaseStmtClass:
4780 case Stmt::DefaultStmtClass:
4781 if (Case == S)
4782 Case = nullptr;
4783 break;
4784
4785 case Stmt::IfStmtClass: {
4786 // FIXME: Precompute which side of an 'if' we would jump to, and go
4787 // straight there rather than scanning both sides.
4788 const IfStmt *IS = cast<IfStmt>(S);
4789
4790 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4791 // preceded by our switch label.
4792 BlockScopeRAII Scope(Info);
4793
4794 // Step into the init statement in case it brings an (uninitialized)
4795 // variable into scope.
4796 if (const Stmt *Init = IS->getInit()) {
4797 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4798 if (ESR != ESR_CaseNotFound) {
4799 assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail
("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4799, __PRETTY_FUNCTION__))
;
4800 return ESR;
4801 }
4802 }
4803
4804 // Condition variable must be initialized if it exists.
4805 // FIXME: We can skip evaluating the body if there's a condition
4806 // variable, as there can't be any case labels within it.
4807 // (The same is true for 'for' statements.)
4808
4809 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4810 if (ESR == ESR_Failed)
4811 return ESR;
4812 if (ESR != ESR_CaseNotFound)
4813 return Scope.destroy() ? ESR : ESR_Failed;
4814 if (!IS->getElse())
4815 return ESR_CaseNotFound;
4816
4817 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4818 if (ESR == ESR_Failed)
4819 return ESR;
4820 if (ESR != ESR_CaseNotFound)
4821 return Scope.destroy() ? ESR : ESR_Failed;
4822 return ESR_CaseNotFound;
4823 }
4824
4825 case Stmt::WhileStmtClass: {
4826 EvalStmtResult ESR =
4827 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4828 if (ESR != ESR_Continue)
4829 return ESR;
4830 break;
4831 }
4832
4833 case Stmt::ForStmtClass: {
4834 const ForStmt *FS = cast<ForStmt>(S);
4835 BlockScopeRAII Scope(Info);
4836
4837 // Step into the init statement in case it brings an (uninitialized)
4838 // variable into scope.
4839 if (const Stmt *Init = FS->getInit()) {
4840 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4841 if (ESR != ESR_CaseNotFound) {
4842 assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail
("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 4842, __PRETTY_FUNCTION__))
;
4843 return ESR;
4844 }
4845 }
4846
4847 EvalStmtResult ESR =
4848 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4849 if (ESR != ESR_Continue)
4850 return ESR;
4851 if (FS->getInc()) {
4852 FullExpressionRAII IncScope(Info);
4853 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4854 return ESR_Failed;
4855 }
4856 break;
4857 }
4858
4859 case Stmt::DeclStmtClass: {
4860 // Start the lifetime of any uninitialized variables we encounter. They
4861 // might be used by the selected branch of the switch.
4862 const DeclStmt *DS = cast<DeclStmt>(S);
4863 for (const auto *D : DS->decls()) {
4864 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4865 if (VD->hasLocalStorage() && !VD->getInit())
4866 if (!EvaluateVarDecl(Info, VD))
4867 return ESR_Failed;
4868 // FIXME: If the variable has initialization that can't be jumped
4869 // over, bail out of any immediately-surrounding compound-statement
4870 // too. There can't be any case labels here.
4871 }
4872 }
4873 return ESR_CaseNotFound;
4874 }
4875
4876 default:
4877 return ESR_CaseNotFound;
4878 }
4879 }
4880
4881 switch (S->getStmtClass()) {
4882 default:
4883 if (const Expr *E = dyn_cast<Expr>(S)) {
4884 // Don't bother evaluating beyond an expression-statement which couldn't
4885 // be evaluated.
4886 // FIXME: Do we need the FullExpressionRAII object here?
4887 // VisitExprWithCleanups should create one when necessary.
4888 FullExpressionRAII Scope(Info);
4889 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4890 return ESR_Failed;
4891 return ESR_Succeeded;
4892 }
4893
4894 Info.FFDiag(S->getBeginLoc());
4895 return ESR_Failed;
4896
4897 case Stmt::NullStmtClass:
4898 return ESR_Succeeded;
4899
4900 case Stmt::DeclStmtClass: {
4901 const DeclStmt *DS = cast<DeclStmt>(S);
4902 for (const auto *D : DS->decls()) {
4903 // Each declaration initialization is its own full-expression.
4904 FullExpressionRAII Scope(Info);
4905 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4906 return ESR_Failed;
4907 if (!Scope.destroy())
4908 return ESR_Failed;
4909 }
4910 return ESR_Succeeded;
4911 }
4912
4913 case Stmt::ReturnStmtClass: {
4914 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4915 FullExpressionRAII Scope(Info);
4916 if (RetExpr &&
4917 !(Result.Slot
4918 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4919 : Evaluate(Result.Value, Info, RetExpr)))
4920 return ESR_Failed;
4921 return Scope.destroy() ? ESR_Returned : ESR_Failed;
4922 }
4923
4924 case Stmt::CompoundStmtClass: {
4925 BlockScopeRAII Scope(Info);
4926
4927 const CompoundStmt *CS = cast<CompoundStmt>(S);
4928 for (const auto *BI : CS->body()) {
4929 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4930 if (ESR == ESR_Succeeded)
4931 Case = nullptr;
4932 else if (ESR != ESR_CaseNotFound) {
4933 if (ESR != ESR_Failed && !Scope.destroy())
4934 return ESR_Failed;
4935 return ESR;
4936 }
4937 }
4938 if (Case)
4939 return ESR_CaseNotFound;
4940 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4941 }
4942
4943 case Stmt::IfStmtClass: {
4944 const IfStmt *IS = cast<IfStmt>(S);
4945
4946 // Evaluate the condition, as either a var decl or as an expression.
4947 BlockScopeRAII Scope(Info);
4948 if (const Stmt *Init = IS->getInit()) {
4949 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4950 if (ESR != ESR_Succeeded) {
4951 if (ESR != ESR_Failed && !Scope.destroy())
4952 return ESR_Failed;
4953 return ESR;
4954 }
4955 }
4956 bool Cond;
4957 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4958 return ESR_Failed;
4959
4960 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4961 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4962 if (ESR != ESR_Succeeded) {
4963 if (ESR != ESR_Failed && !Scope.destroy())
4964 return ESR_Failed;
4965 return ESR;
4966 }
4967 }
4968 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4969 }
4970
4971 case Stmt::WhileStmtClass: {
4972 const WhileStmt *WS = cast<WhileStmt>(S);
4973 while (true) {
4974 BlockScopeRAII Scope(Info);
4975 bool Continue;
4976 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4977 Continue))
4978 return ESR_Failed;
4979 if (!Continue)
4980 break;
4981
4982 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4983 if (ESR != ESR_Continue) {
4984 if (ESR != ESR_Failed && !Scope.destroy())
4985 return ESR_Failed;
4986 return ESR;
4987 }
4988 if (!Scope.destroy())
4989 return ESR_Failed;
4990 }
4991 return ESR_Succeeded;
4992 }
4993
4994 case Stmt::DoStmtClass: {
4995 const DoStmt *DS = cast<DoStmt>(S);
4996 bool Continue;
4997 do {
4998 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4999 if (ESR != ESR_Continue)
5000 return ESR;
5001 Case = nullptr;
5002
5003 FullExpressionRAII CondScope(Info);
5004 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5005 !CondScope.destroy())
5006 return ESR_Failed;
5007 } while (Continue);
5008 return ESR_Succeeded;
5009 }
5010
5011 case Stmt::ForStmtClass: {
5012 const ForStmt *FS = cast<ForStmt>(S);
5013 BlockScopeRAII ForScope(Info);
5014 if (FS->getInit()) {
5015 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5016 if (ESR != ESR_Succeeded) {
5017 if (ESR != ESR_Failed && !ForScope.destroy())
5018 return ESR_Failed;
5019 return ESR;
5020 }
5021 }
5022 while (true) {
5023 BlockScopeRAII IterScope(Info);
5024 bool Continue = true;
5025 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5026 FS->getCond(), Continue))
5027 return ESR_Failed;
5028 if (!Continue)
5029 break;
5030
5031 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5032 if (ESR != ESR_Continue) {
5033 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5034 return ESR_Failed;
5035 return ESR;
5036 }
5037
5038 if (FS->getInc()) {
5039 FullExpressionRAII IncScope(Info);
5040 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5041 return ESR_Failed;
5042 }
5043
5044 if (!IterScope.destroy())
5045 return ESR_Failed;
5046 }
5047 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5048 }
5049
5050 case Stmt::CXXForRangeStmtClass: {
5051 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5052 BlockScopeRAII Scope(Info);
5053
5054 // Evaluate the init-statement if present.
5055 if (FS->getInit()) {
5056 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5057 if (ESR != ESR_Succeeded) {
5058 if (ESR != ESR_Failed && !Scope.destroy())
5059 return ESR_Failed;
5060 return ESR;
5061 }
5062 }
5063
5064 // Initialize the __range variable.
5065 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5066 if (ESR != ESR_Succeeded) {
5067 if (ESR != ESR_Failed && !Scope.destroy())
5068 return ESR_Failed;
5069 return ESR;
5070 }
5071
5072 // Create the __begin and __end iterators.
5073 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5074 if (ESR != ESR_Succeeded) {
5075 if (ESR != ESR_Failed && !Scope.destroy())
5076 return ESR_Failed;
5077 return ESR;
5078 }
5079 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5080 if (ESR != ESR_Succeeded) {
5081 if (ESR != ESR_Failed && !Scope.destroy())
5082 return ESR_Failed;
5083 return ESR;
5084 }
5085
5086 while (true) {
5087 // Condition: __begin != __end.
5088 {
5089 bool Continue = true;
5090 FullExpressionRAII CondExpr(Info);
5091 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5092 return ESR_Failed;
5093 if (!Continue)
5094 break;
5095 }
5096
5097 // User's variable declaration, initialized by *__begin.
5098 BlockScopeRAII InnerScope(Info);
5099 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5100 if (ESR != ESR_Succeeded) {
5101 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5102 return ESR_Failed;
5103 return ESR;
5104 }
5105
5106 // Loop body.
5107 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5108 if (ESR != ESR_Continue) {
5109 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5110 return ESR_Failed;
5111 return ESR;
5112 }
5113
5114 // Increment: ++__begin
5115 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5116 return ESR_Failed;
5117
5118 if (!InnerScope.destroy())
5119 return ESR_Failed;
5120 }
5121
5122 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5123 }
5124
5125 case Stmt::SwitchStmtClass:
5126 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5127
5128 case Stmt::ContinueStmtClass:
5129 return ESR_Continue;
5130
5131 case Stmt::BreakStmtClass:
5132 return ESR_Break;
5133
5134 case Stmt::LabelStmtClass:
5135 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5136
5137 case Stmt::AttributedStmtClass:
5138 // As a general principle, C++11 attributes can be ignored without
5139 // any semantic impact.
5140 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5141 Case);
5142
5143 case Stmt::CaseStmtClass:
5144 case Stmt::DefaultStmtClass:
5145 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5146 case Stmt::CXXTryStmtClass:
5147 // Evaluate try blocks by evaluating all sub statements.
5148 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5149 }
5150}
5151
5152/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5153/// default constructor. If so, we'll fold it whether or not it's marked as
5154/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5155/// so we need special handling.
5156static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5157 const CXXConstructorDecl *CD,
5158 bool IsValueInitialization) {
5159 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5160 return false;
5161
5162 // Value-initialization does not call a trivial default constructor, so such a
5163 // call is a core constant expression whether or not the constructor is
5164 // constexpr.
5165 if (!CD->isConstexpr() && !IsValueInitialization) {
5166 if (Info.getLangOpts().CPlusPlus11) {
5167 // FIXME: If DiagDecl is an implicitly-declared special member function,
5168 // we should be much more explicit about why it's not constexpr.
5169 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5170 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5171 Info.Note(CD->getLocation(), diag::note_declared_at);
5172 } else {
5173 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5174 }
5175 }
5176 return true;
5177}
5178
5179/// CheckConstexprFunction - Check that a function can be called in a constant
5180/// expression.
5181static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5182 const FunctionDecl *Declaration,
5183 const FunctionDecl *Definition,
5184 const Stmt *Body) {
5185 // Potential constant expressions can contain calls to declared, but not yet
5186 // defined, constexpr functions.
5187 if (Info.checkingPotentialConstantExpression() && !Definition &&
5188 Declaration->isConstexpr())
5189 return false;
5190
5191 // Bail out if the function declaration itself is invalid. We will
5192 // have produced a relevant diagnostic while parsing it, so just
5193 // note the problematic sub-expression.
5194 if (Declaration->isInvalidDecl()) {
5195 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5196 return false;
5197 }
5198
5199 // DR1872: An instantiated virtual constexpr function can't be called in a
5200 // constant expression (prior to C++20). We can still constant-fold such a
5201 // call.
5202 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5203 cast<CXXMethodDecl>(Declaration)->isVirtual())
5204 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5205
5206 if (Definition && Definition->isInvalidDecl()) {
5207 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5208 return false;
5209 }
5210
5211 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5212 for (const auto *InitExpr : CtorDecl->inits()) {
5213 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5214 return false;
5215 }
5216 }
5217
5218 // Can we evaluate this function call?
5219 if (Definition && Definition->isConstexpr() && Body)
5220 return true;
5221
5222 if (Info.getLangOpts().CPlusPlus11) {
5223 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5224
5225 // If this function is not constexpr because it is an inherited
5226 // non-constexpr constructor, diagnose that directly.
5227 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5228 if (CD && CD->isInheritingConstructor()) {
5229 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5230 if (!Inherited->isConstexpr())
5231 DiagDecl = CD = Inherited;
5232 }
5233
5234 // FIXME: If DiagDecl is an implicitly-declared special member function
5235 // or an inheriting constructor, we should be much more explicit about why
5236 // it's not constexpr.
5237 if (CD && CD->isInheritingConstructor())
5238 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5239 << CD->getInheritedConstructor().getConstructor()->getParent();
5240 else
5241 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5242 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5243 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5244 } else {
5245 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5246 }
5247 return false;
5248}
5249
5250namespace {
5251struct CheckDynamicTypeHandler {
5252 AccessKinds AccessKind;
5253 typedef bool result_type;
5254 bool failed() { return false; }
5255 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5256 bool found(APSInt &Value, QualType SubobjType) { return true; }
5257 bool found(APFloat &Value, QualType SubobjType) { return true; }
5258};
5259} // end anonymous namespace
5260
5261/// Check that we can access the notional vptr of an object / determine its
5262/// dynamic type.
5263static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5264 AccessKinds AK, bool Polymorphic) {
5265 if (This.Designator.Invalid)
5266 return false;
5267
5268 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5269
5270 if (!Obj)
5271 return false;
5272
5273 if (!Obj.Value) {
5274 // The object is not usable in constant expressions, so we can't inspect
5275 // its value to see if it's in-lifetime or what the active union members
5276 // are. We can still check for a one-past-the-end lvalue.
5277 if (This.Designator.isOnePastTheEnd() ||
5278 This.Designator.isMostDerivedAnUnsizedArray()) {
5279 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5280 ? diag::note_constexpr_access_past_end
5281 : diag::note_constexpr_access_unsized_array)
5282 << AK;
5283 return false;
5284 } else if (Polymorphic) {
5285 // Conservatively refuse to perform a polymorphic operation if we would
5286 // not be able to read a notional 'vptr' value.
5287 APValue Val;
5288 This.moveInto(Val);
5289 QualType StarThisType =
5290 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5291 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5292 << AK << Val.getAsString(Info.Ctx, StarThisType);
5293 return false;
5294 }
5295 return true;
5296 }
5297
5298 CheckDynamicTypeHandler Handler{AK};
5299 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5300}
5301
5302/// Check that the pointee of the 'this' pointer in a member function call is
5303/// either within its lifetime or in its period of construction or destruction.
5304static bool
5305checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5306 const LValue &This,
5307 const CXXMethodDecl *NamedMember) {
5308 return checkDynamicType(
5309 Info, E, This,
5310 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5311}
5312
5313struct DynamicType {
5314 /// The dynamic class type of the object.
5315 const CXXRecordDecl *Type;
5316 /// The corresponding path length in the lvalue.
5317 unsigned PathLength;
5318};
5319
5320static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5321 unsigned PathLength) {
5322 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5323, __PRETTY_FUNCTION__))
5323 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5323, __PRETTY_FUNCTION__))
;
5324 return (PathLength == Designator.MostDerivedPathLength)
5325 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5326 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5327}
5328
5329/// Determine the dynamic type of an object.
5330static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5331 LValue &This, AccessKinds AK) {
5332 // If we don't have an lvalue denoting an object of class type, there is no
5333 // meaningful dynamic type. (We consider objects of non-class type to have no
5334 // dynamic type.)
5335 if (!checkDynamicType(Info, E, This, AK, true))
5336 return None;
5337
5338 // Refuse to compute a dynamic type in the presence of virtual bases. This
5339 // shouldn't happen other than in constant-folding situations, since literal
5340 // types can't have virtual bases.
5341 //
5342 // Note that consumers of DynamicType assume that the type has no virtual
5343 // bases, and will need modifications if this restriction is relaxed.
5344 const CXXRecordDecl *Class =
5345 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5346 if (!Class || Class->getNumVBases()) {
5347 Info.FFDiag(E);
5348 return None;
5349 }
5350
5351 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5352 // binary search here instead. But the overwhelmingly common case is that
5353 // we're not in the middle of a constructor, so it probably doesn't matter
5354 // in practice.
5355 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5356 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5357 PathLength <= Path.size(); ++PathLength) {
5358 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5359 Path.slice(0, PathLength))) {
5360 case ConstructionPhase::Bases:
5361 case ConstructionPhase::DestroyingBases:
5362 // We're constructing or destroying a base class. This is not the dynamic
5363 // type.
5364 break;
5365
5366 case ConstructionPhase::None:
5367 case ConstructionPhase::AfterBases:
5368 case ConstructionPhase::AfterFields:
5369 case ConstructionPhase::Destroying:
5370 // We've finished constructing the base classes and not yet started
5371 // destroying them again, so this is the dynamic type.
5372 return DynamicType{getBaseClassType(This.Designator, PathLength),
5373 PathLength};
5374 }
5375 }
5376
5377 // CWG issue 1517: we're constructing a base class of the object described by
5378 // 'This', so that object has not yet begun its period of construction and
5379 // any polymorphic operation on it results in undefined behavior.
5380 Info.FFDiag(E);
5381 return None;
5382}
5383
5384/// Perform virtual dispatch.
5385static const CXXMethodDecl *HandleVirtualDispatch(
5386 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5387 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5388 Optional<DynamicType> DynType = ComputeDynamicType(
5389 Info, E, This,
5390 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5391 if (!DynType)
5392 return nullptr;
5393
5394 // Find the final overrider. It must be declared in one of the classes on the
5395 // path from the dynamic type to the static type.
5396 // FIXME: If we ever allow literal types to have virtual base classes, that
5397 // won't be true.
5398 const CXXMethodDecl *Callee = Found;
5399 unsigned PathLength = DynType->PathLength;
5400 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5401 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5402 const CXXMethodDecl *Overrider =
5403 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5404 if (Overrider) {
5405 Callee = Overrider;
5406 break;
5407 }
5408 }
5409
5410 // C++2a [class.abstract]p6:
5411 // the effect of making a virtual call to a pure virtual function [...] is
5412 // undefined
5413 if (Callee->isPure()) {
5414 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5415 Info.Note(Callee->getLocation(), diag::note_declared_at);
5416 return nullptr;
5417 }
5418
5419 // If necessary, walk the rest of the path to determine the sequence of
5420 // covariant adjustment steps to apply.
5421 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5422 Found->getReturnType())) {
5423 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5424 for (unsigned CovariantPathLength = PathLength + 1;
5425 CovariantPathLength != This.Designator.Entries.size();
5426 ++CovariantPathLength) {
5427 const CXXRecordDecl *NextClass =
5428 getBaseClassType(This.Designator, CovariantPathLength);
5429 const CXXMethodDecl *Next =
5430 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5431 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5432 Next->getReturnType(), CovariantAdjustmentPath.back()))
5433 CovariantAdjustmentPath.push_back(Next->getReturnType());
5434 }
5435 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5436 CovariantAdjustmentPath.back()))
5437 CovariantAdjustmentPath.push_back(Found->getReturnType());
5438 }
5439
5440 // Perform 'this' adjustment.
5441 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5442 return nullptr;
5443
5444 return Callee;
5445}
5446
5447/// Perform the adjustment from a value returned by a virtual function to
5448/// a value of the statically expected type, which may be a pointer or
5449/// reference to a base class of the returned type.
5450static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5451 APValue &Result,
5452 ArrayRef<QualType> Path) {
5453 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5454, __PRETTY_FUNCTION__))
5454 "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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5454, __PRETTY_FUNCTION__))
;
5455 if (Result.isNullPointer())
5456 return true;
5457
5458 LValue LVal;
5459 LVal.setFrom(Info.Ctx, Result);
5460
5461 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5462 for (unsigned I = 1; I != Path.size(); ++I) {
5463 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5464 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5464, __PRETTY_FUNCTION__))
;
5465 if (OldClass != NewClass &&
5466 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5467 return false;
5468 OldClass = NewClass;
5469 }
5470
5471 LVal.moveInto(Result);
5472 return true;
5473}
5474
5475/// Determine whether \p Base, which is known to be a direct base class of
5476/// \p Derived, is a public base class.
5477static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5478 const CXXRecordDecl *Base) {
5479 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5480 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5481 if (BaseClass && declaresSameEntity(BaseClass, Base))
5482 return BaseSpec.getAccessSpecifier() == AS_public;
5483 }
5484 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5484)
;
5485}
5486
5487/// Apply the given dynamic cast operation on the provided lvalue.
5488///
5489/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5490/// to find a suitable target subobject.
5491static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5492 LValue &Ptr) {
5493 // We can't do anything with a non-symbolic pointer value.
5494 SubobjectDesignator &D = Ptr.Designator;
5495 if (D.Invalid)
5496 return false;
5497
5498 // C++ [expr.dynamic.cast]p6:
5499 // If v is a null pointer value, the result is a null pointer value.
5500 if (Ptr.isNullPointer() && !E->isGLValue())
5501 return true;
5502
5503 // For all the other cases, we need the pointer to point to an object within
5504 // its lifetime / period of construction / destruction, and we need to know
5505 // its dynamic type.
5506 Optional<DynamicType> DynType =
5507 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5508 if (!DynType)
5509 return false;
5510
5511 // C++ [expr.dynamic.cast]p7:
5512 // If T is "pointer to cv void", then the result is a pointer to the most
5513 // derived object
5514 if (E->getType()->isVoidPointerType())
5515 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5516
5517 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5518 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5518, __PRETTY_FUNCTION__))
;
5519 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5520
5521 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5522 // C++ [expr.dynamic.cast]p9:
5523 if (!E->isGLValue()) {
5524 // The value of a failed cast to pointer type is the null pointer value
5525 // of the required result type.
5526 Ptr.setNull(Info.Ctx, E->getType());
5527 return true;
5528 }
5529
5530 // A failed cast to reference type throws [...] std::bad_cast.
5531 unsigned DiagKind;
5532 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5533 DynType->Type->isDerivedFrom(C)))
5534 DiagKind = 0;
5535 else if (!Paths || Paths->begin() == Paths->end())
5536 DiagKind = 1;
5537 else if (Paths->isAmbiguous(CQT))
5538 DiagKind = 2;
5539 else {
5540 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5540, __PRETTY_FUNCTION__))
;
5541 DiagKind = 3;
5542 }
5543 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5544 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5545 << Info.Ctx.getRecordType(DynType->Type)
5546 << E->getType().getUnqualifiedType();
5547 return false;
5548 };
5549
5550 // Runtime check, phase 1:
5551 // Walk from the base subobject towards the derived object looking for the
5552 // target type.
5553 for (int PathLength = Ptr.Designator.Entries.size();
5554 PathLength >= (int)DynType->PathLength; --PathLength) {
5555 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5556 if (declaresSameEntity(Class, C))
5557 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5558 // We can only walk across public inheritance edges.
5559 if (PathLength > (int)DynType->PathLength &&
5560 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5561 Class))
5562 return RuntimeCheckFailed(nullptr);
5563 }
5564
5565 // Runtime check, phase 2:
5566 // Search the dynamic type for an unambiguous public base of type C.
5567 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5568 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5569 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5570 Paths.front().Access == AS_public) {
5571 // Downcast to the dynamic type...
5572 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5573 return false;
5574 // ... then upcast to the chosen base class subobject.
5575 for (CXXBasePathElement &Elem : Paths.front())
5576 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5577 return false;
5578 return true;
5579 }
5580
5581 // Otherwise, the runtime check fails.
5582 return RuntimeCheckFailed(&Paths);
5583}
5584
5585namespace {
5586struct StartLifetimeOfUnionMemberHandler {
5587 EvalInfo &Info;
5588 const Expr *LHSExpr;
5589 const FieldDecl *Field;
5590 bool DuringInit;
5591 bool Failed = false;
5592 static const AccessKinds AccessKind = AK_Assign;
5593
5594 typedef bool result_type;
5595 bool failed() { return Failed; }
5596 bool found(APValue &Subobj, QualType SubobjType) {
5597 // We are supposed to perform no initialization but begin the lifetime of
5598 // the object. We interpret that as meaning to do what default
5599 // initialization of the object would do if all constructors involved were
5600 // trivial:
5601 // * All base, non-variant member, and array element subobjects' lifetimes
5602 // begin
5603 // * No variant members' lifetimes begin
5604 // * All scalar subobjects whose lifetimes begin have indeterminate values
5605 assert(SubobjType->isUnionType())((SubobjType->isUnionType()) ? static_cast<void> (0)
: __assert_fail ("SubobjType->isUnionType()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5605, __PRETTY_FUNCTION__))
;
5606 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5607 // This union member is already active. If it's also in-lifetime, there's
5608 // nothing to do.
5609 if (Subobj.getUnionValue().hasValue())
5610 return true;
5611 } else if (DuringInit) {
5612 // We're currently in the process of initializing a different union
5613 // member. If we carried on, that initialization would attempt to
5614 // store to an inactive union member, resulting in undefined behavior.
5615 Info.FFDiag(LHSExpr,
5616 diag::note_constexpr_union_member_change_during_init);
5617 return false;
5618 }
5619 APValue Result;
5620 Failed = !getDefaultInitValue(Field->getType(), Result);
5621 Subobj.setUnion(Field, Result);
5622 return true;
5623 }
5624 bool found(APSInt &Value, QualType SubobjType) {
5625 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5625)
;
5626 }
5627 bool found(APFloat &Value, QualType SubobjType) {
5628 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5628)
;
5629 }
5630};
5631} // end anonymous namespace
5632
5633const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5634
5635/// Handle a builtin simple-assignment or a call to a trivial assignment
5636/// operator whose left-hand side might involve a union member access. If it
5637/// does, implicitly start the lifetime of any accessed union elements per
5638/// C++20 [class.union]5.
5639static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5640 const LValue &LHS) {
5641 if (LHS.InvalidBase || LHS.Designator.Invalid)
5642 return false;
5643
5644 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5645 // C++ [class.union]p5:
5646 // define the set S(E) of subexpressions of E as follows:
5647 unsigned PathLength = LHS.Designator.Entries.size();
5648 for (const Expr *E = LHSExpr; E != nullptr;) {
5649 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5650 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5651 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5652 // Note that we can't implicitly start the lifetime of a reference,
5653 // so we don't need to proceed any further if we reach one.
5654 if (!FD || FD->getType()->isReferenceType())
5655 break;
5656
5657 // ... and also contains A.B if B names a union member ...
5658 if (FD->getParent()->isUnion()) {
5659 // ... of a non-class, non-array type, or of a class type with a
5660 // trivial default constructor that is not deleted, or an array of
5661 // such types.
5662 auto *RD =
5663 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5664 if (!RD || RD->hasTrivialDefaultConstructor())
5665 UnionPathLengths.push_back({PathLength - 1, FD});
5666 }
5667
5668 E = ME->getBase();
5669 --PathLength;
5670 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5672, __PRETTY_FUNCTION__))
5671 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5672, __PRETTY_FUNCTION__))
5672 .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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5672, __PRETTY_FUNCTION__))
;
5673
5674 // -- If E is of the form A[B] and is interpreted as a built-in array
5675 // subscripting operator, S(E) is [S(the array operand, if any)].
5676 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5677 // Step over an ArrayToPointerDecay implicit cast.
5678 auto *Base = ASE->getBase()->IgnoreImplicit();
5679 if (!Base->getType()->isArrayType())
5680 break;
5681
5682 E = Base;
5683 --PathLength;
5684
5685 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5686 // Step over a derived-to-base conversion.
5687 E = ICE->getSubExpr();
5688 if (ICE->getCastKind() == CK_NoOp)
5689 continue;
5690 if (ICE->getCastKind() != CK_DerivedToBase &&
5691 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5692 break;
5693 // Walk path backwards as we walk up from the base to the derived class.
5694 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5695 --PathLength;
5696 (void)Elt;
5697 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5699, __PRETTY_FUNCTION__))
5698 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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5699, __PRETTY_FUNCTION__))
5699 .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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5699, __PRETTY_FUNCTION__))
;
5700 }
5701
5702 // -- Otherwise, S(E) is empty.
5703 } else {
5704 break;
5705 }
5706 }
5707
5708 // Common case: no unions' lifetimes are started.
5709 if (UnionPathLengths.empty())
5710 return true;
5711
5712 // if modification of X [would access an inactive union member], an object
5713 // of the type of X is implicitly created
5714 CompleteObject Obj =
5715 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5716 if (!Obj)
5717 return false;
5718 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5719 llvm::reverse(UnionPathLengths)) {
5720 // Form a designator for the union object.
5721 SubobjectDesignator D = LHS.Designator;
5722 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5723
5724 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5725 ConstructionPhase::AfterBases;
5726 StartLifetimeOfUnionMemberHandler StartLifetime{
5727 Info, LHSExpr, LengthAndField.second, DuringInit};
5728 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5729 return false;
5730 }
5731
5732 return true;
5733}
5734
5735namespace {
5736typedef SmallVector<APValue, 8> ArgVector;
5737}
5738
5739/// EvaluateArgs - Evaluate the arguments to a function call.
5740static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5741 EvalInfo &Info, const FunctionDecl *Callee) {
5742 bool Success = true;
5743 llvm::SmallBitVector ForbiddenNullArgs;
5744 if (Callee->hasAttr<NonNullAttr>()) {
5745 ForbiddenNullArgs.resize(Args.size());
5746 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5747 if (!Attr->args_size()) {
5748 ForbiddenNullArgs.set();
5749 break;
5750 } else
5751 for (auto Idx : Attr->args()) {
5752 unsigned ASTIdx = Idx.getASTIndex();
5753 if (ASTIdx >= Args.size())
5754 continue;
5755 ForbiddenNullArgs[ASTIdx] = 1;
5756 }
5757 }
5758 }
5759 // FIXME: This is the wrong evaluation order for an assignment operator
5760 // called via operator syntax.
5761 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5762 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5763 // If we're checking for a potential constant expression, evaluate all
5764 // initializers even if some of them fail.
5765 if (!Info.noteFailure())
5766 return false;
5767 Success = false;
5768 } else if (!ForbiddenNullArgs.empty() &&
5769 ForbiddenNullArgs[Idx] &&
5770 ArgValues[Idx].isLValue() &&
5771 ArgValues[Idx].isNullPointer()) {
5772 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5773 if (!Info.noteFailure())
5774 return false;
5775 Success = false;
5776 }
5777 }
5778 return Success;
5779}
5780
5781/// Evaluate a function call.
5782static bool HandleFunctionCall(SourceLocation CallLoc,
5783 const FunctionDecl *Callee, const LValue *This,
5784 ArrayRef<const Expr*> Args, const Stmt *Body,
5785 EvalInfo &Info, APValue &Result,
5786 const LValue *ResultSlot) {
5787 ArgVector ArgValues(Args.size());
5788 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5789 return false;
5790
5791 if (!Info.CheckCallLimit(CallLoc))
5792 return false;
5793
5794 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5795
5796 // For a trivial copy or move assignment, perform an APValue copy. This is
5797 // essential for unions, where the operations performed by the assignment
5798 // operator cannot be represented as statements.
5799 //
5800 // Skip this for non-union classes with no fields; in that case, the defaulted
5801 // copy/move does not actually read the object.
5802 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5803 if (MD && MD->isDefaulted() &&
5804 (MD->getParent()->isUnion() ||
5805 (MD->isTrivial() &&
5806 isReadByLvalueToRvalueConversion(MD->getParent())))) {
5807 assert(This &&((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5808, __PRETTY_FUNCTION__))
5808 (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~++20200917111122+b03c2b8395b/clang/lib/AST/ExprConstant.cpp"
, 5808, __PRETTY_FUNCTION__))
;
5809 LValue RHS;
5810 RHS.setFrom(Info.Ctx, ArgValues[0]);
5811 APValue RHSValue;
5812 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5813 RHSValue, MD->getParent()->isUnion()))
5814 return false;
5815 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5816 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5817 return false;
5818 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5819 RHSValue))
5820 return false;
5821 This->moveInto(Result);
5822 return true;
5823 } else if (MD && isLambdaCallOperator(MD)) {
5824 // We're in a lambda; determine the lambda capture field maps unless we're
5825 // just constexpr checking a lambda's call operator. constexpr checking is
5826 // done before the captures have been added to the closure object (unless
5827 // we're inferring constexpr-ness), so we don't have access to them in this
5828 // case. But since we don't need the captures to constexpr check, we can
5829 // just ignore them.
5830 if (!Info.checkingPotentialConstantExpression())
5831 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5832 Frame.LambdaThisCaptureField);
5833 }
5834
5835 StmtResult Ret = {Result, ResultSlot};
5836 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5837 if (ESR == ESR_Succeeded) {
5838 if (Callee->getReturnType()->isVoidType())
5839 return true;
5840 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5841 }
5842 return ESR == ESR_Returned;
5843}
5844
5845/// Evaluate a constructor call.
5846static bool HandleConstructorCall(const Expr *E, const LValue &This,
5847 APValue *ArgValues,
5848 const CXXConstructorDecl *Definition,
5849 EvalInfo &Info, APValue &Result) {
5850 SourceLocation CallLoc = E->getExprLoc();
5851 if (!Info.CheckCallLimit(CallLoc))
5852 return false;
5853
5854 const CXXRecordDecl *RD = Definition->getParent();
5855 if (RD->getNumVBases()) {
5856 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5857 return false;
5858 }
5859
5860 EvalInfo::EvaluatingConstructorRAII EvalObj(
5861 Info,
5862 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5863 RD->getNumBases());
5864 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5865
5866 // FIXME: Creating an APValue just to hold a nonexistent return value is
5867 // wasteful.
5868 APValue RetVal;
5869 StmtResult Ret = {RetVal, nullptr};
5870
5871 // If it's a delegating constructor, delegate.
5872 if (Definition->isDelegatingConstructor()) {
5873 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5874 {
5875 FullExpressionRAII InitScope(Info);
5876 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5877 !InitScope.destroy())
5878 return false;
5879 }
5880 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5881 }
5882
5883 // For a trivial copy or move constructor, perform an APValue copy. This is
5884 // essential for unions (or classes with anonymous union members), where the
5885 // operations performed by the constructor cannot be represented by
5886 // ctor-initializers.
5887 //
5888 // Skip this for empty non-union classes; we should not perform an
5889 // lvalue-to-rvalue conversion on them because their copy constructor does not
5890 // actually read them.
5891 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5892 (Definition->getParent()->isUnion() ||
5893 (Definition->isTrivial() &&
5894 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5895 LValue RHS;
5896 RHS.setFrom(Info.Ctx, ArgValues[0]);
5897 return handleLValueToRValueConversion(
5898 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5899 RHS, Result, Definition->getParent()->isUnion());
5900 }
5901
5902 // Reserve space for the struct members.
5903 if (!Result.hasValue()) {
5904 if (!RD->isUnion())
5905 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),