Bug Summary

File:build/source/clang/lib/AST/ExprConstant.cpp
Warning:line 3282, column 10
Access to field 'Callee' results in a dereference of a null pointer (loaded from field 'CurrentCall')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ExprConstant.cpp -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/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/SmallBitVector.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include "llvm/Support/TimeProfiler.h"
59#include "llvm/Support/raw_ostream.h"
60#include <cstring>
61#include <functional>
62#include <optional>
63
64#define DEBUG_TYPE"exprconstant" "exprconstant"
65
66using namespace clang;
67using llvm::APFixedPoint;
68using llvm::APInt;
69using llvm::APSInt;
70using llvm::APFloat;
71using llvm::FixedPointSemantics;
72
73namespace {
74 struct LValue;
75 class CallStackFrame;
76 class EvalInfo;
77
78 using SourceLocExprScopeGuard =
79 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80
81 static QualType getType(APValue::LValueBase B) {
82 return B.getType();
83 }
84
85 /// Get an LValue path entry, which is known to not be an array index, as a
86 /// field declaration.
87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89 }
90 /// Get an LValue path entry, which is known to not be an array index, as a
91 /// base class declaration.
92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94 }
95 /// Determine whether this LValue path entry for a base class names a virtual
96 /// base class.
97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98 return E.getAsBaseOrMember().getInt();
99 }
100
101 /// Given an expression, determine the type used to store the result of
102 /// evaluating that expression.
103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104 if (E->isPRValue())
105 return E->getType();
106 return Ctx.getLValueReferenceType(E->getType());
107 }
108
109 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112 return DirectCallee->getAttr<AllocSizeAttr>();
113 if (const Decl *IndirectCallee = CE->getCalleeDecl())
114 return IndirectCallee->getAttr<AllocSizeAttr>();
115 return nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return getAllocSizeAttr(CE) ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 163)
;
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 176)
;
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191 ArrayRef<APValue::LValuePathEntry> Path,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
197 "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
;
198 unsigned MostDerivedLength = 0;
199 Type = getType(Base);
200
201 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202 if (Type->isArrayType()) {
203 const ArrayType *AT = Ctx.getAsArrayType(Type);
204 Type = AT->getElementType();
205 MostDerivedLength = I + 1;
206 IsArray = true;
207
208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209 ArraySize = CAT->getSize().getZExtValue();
210 } else {
211 assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator"
) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\""
, "clang/lib/AST/ExprConstant.cpp", 211, __extension__ __PRETTY_FUNCTION__
))
;
212 FirstEntryIsUnsizedArray = true;
213 ArraySize = AssumedSizeForUnsizedArray;
214 }
215 } else if (Type->isAnyComplexType()) {
216 const ComplexType *CT = Type->castAs<ComplexType>();
217 Type = CT->getElementType();
218 ArraySize = 2;
219 MostDerivedLength = I + 1;
220 IsArray = true;
221 } else if (const FieldDecl *FD = getAsField(Path[I])) {
222 Type = FD->getType();
223 ArraySize = 0;
224 MostDerivedLength = I + 1;
225 IsArray = false;
226 } else {
227 // Path[I] describes a base class.
228 ArraySize = 0;
229 IsArray = false;
230 }
231 }
232 return MostDerivedLength;
233 }
234
235 /// A path from a glvalue to a subobject of that glvalue.
236 struct SubobjectDesignator {
237 /// True if the subobject was named in a manner not supported by C++11. Such
238 /// lvalues can still be folded, but they are not core constant expressions
239 /// and we cannot perform lvalue-to-rvalue conversions on them.
240 unsigned Invalid : 1;
241
242 /// Is this a pointer one past the end of an object?
243 unsigned IsOnePastTheEnd : 1;
244
245 /// Indicator of whether the first entry is an unsized array.
246 unsigned FirstEntryIsAnUnsizedArray : 1;
247
248 /// Indicator of whether the most-derived object is an array element.
249 unsigned MostDerivedIsArrayElement : 1;
250
251 /// The length of the path to the most-derived object of which this is a
252 /// subobject.
253 unsigned MostDerivedPathLength : 28;
254
255 /// The size of the array of which the most-derived object is an element.
256 /// This will always be 0 if the most-derived object is not an array
257 /// element. 0 is not an indicator of whether or not the most-derived object
258 /// is an array, however, because 0-length arrays are allowed.
259 ///
260 /// If the current array is an unsized array, the value of this is
261 /// undefined.
262 uint64_t MostDerivedArraySize;
263
264 /// The type of the most derived object referred to by this address.
265 QualType MostDerivedType;
266
267 typedef APValue::LValuePathEntry PathEntry;
268
269 /// The entries on the path from the glvalue to the designated subobject.
270 SmallVector<PathEntry, 8> Entries;
271
272 SubobjectDesignator() : Invalid(true) {}
273
274 explicit SubobjectDesignator(QualType T)
275 : Invalid(false), IsOnePastTheEnd(false),
276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277 MostDerivedPathLength(0), MostDerivedArraySize(0),
278 MostDerivedType(T) {}
279
280 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283 MostDerivedPathLength(0), MostDerivedArraySize(0) {
284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\""
, "clang/lib/AST/ExprConstant.cpp", 284, __extension__ __PRETTY_FUNCTION__
))
;
285 if (!Invalid) {
286 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287 ArrayRef<PathEntry> VEntries = V.getLValuePath();
288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289 if (V.getLValueBase()) {
290 bool IsArray = false;
291 bool FirstIsUnsizedArray = false;
292 MostDerivedPathLength = findMostDerivedSubobject(
293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294 MostDerivedType, IsArray, FirstIsUnsizedArray);
295 MostDerivedIsArrayElement = IsArray;
296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297 }
298 }
299 }
300
301 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302 unsigned NewLength) {
303 if (Invalid)
304 return;
305
306 assert(Base && "cannot truncate path for null pointer")(static_cast <bool> (Base && "cannot truncate path for null pointer"
) ? void (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\""
, "clang/lib/AST/ExprConstant.cpp", 306, __extension__ __PRETTY_FUNCTION__
))
;
307 assert(NewLength <= Entries.size() && "not a truncation")(static_cast <bool> (NewLength <= Entries.size() &&
"not a truncation") ? void (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\""
, "clang/lib/AST/ExprConstant.cpp", 307, __extension__ __PRETTY_FUNCTION__
))
;
308
309 if (NewLength == Entries.size())
310 return;
311 Entries.resize(NewLength);
312
313 bool IsArray = false;
314 bool FirstIsUnsizedArray = false;
315 MostDerivedPathLength = findMostDerivedSubobject(
316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317 FirstIsUnsizedArray);
318 MostDerivedIsArrayElement = IsArray;
319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320 }
321
322 void setInvalid() {
323 Invalid = true;
324 Entries.clear();
325 }
326
327 /// Determine whether the most derived subobject is an array without a
328 /// known bound.
329 bool isMostDerivedAnUnsizedArray() const {
330 assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators"
) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\""
, "clang/lib/AST/ExprConstant.cpp", 330, __extension__ __PRETTY_FUNCTION__
))
;
331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332 }
333
334 /// Determine what the most derived array's size is. Results in an assertion
335 /// failure if the most derived array lacks a size.
336 uint64_t getMostDerivedArraySize() const {
337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() &&
"Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\""
, "clang/lib/AST/ExprConstant.cpp", 337, __extension__ __PRETTY_FUNCTION__
))
;
338 return MostDerivedArraySize;
339 }
340
341 /// Determine whether this is a one-past-the-end pointer.
342 bool isOnePastTheEnd() const {
343 assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail
("!Invalid", "clang/lib/AST/ExprConstant.cpp", 343, __extension__
__PRETTY_FUNCTION__))
;
344 if (IsOnePastTheEnd)
345 return true;
346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348 MostDerivedArraySize)
349 return true;
350 return false;
351 }
352
353 /// Get the range of valid index adjustments in the form
354 /// {maximum value that can be subtracted from this pointer,
355 /// maximum value that can be added to this pointer}
356 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357 if (Invalid || isMostDerivedAnUnsizedArray())
358 return {0, 0};
359
360 // [expr.add]p4: For the purposes of these operators, a pointer to a
361 // nonarray object behaves the same as a pointer to the first element of
362 // an array of length one with the type of the object as its element type.
363 bool IsArray = MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement;
365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366 : (uint64_t)IsOnePastTheEnd;
367 uint64_t ArraySize =
368 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369 return {ArrayIndex, ArraySize - ArrayIndex};
370 }
371
372 /// Check that this refers to a valid subobject.
373 bool isValidSubobject() const {
374 if (Invalid)
375 return false;
376 return !isOnePastTheEnd();
377 }
378 /// Check that this refers to a valid subobject, and if not, produce a
379 /// relevant diagnostic and set the designator as invalid.
380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381
382 /// Get the type of the designated object.
383 QualType getType(ASTContext &Ctx) const {
384 assert(!Invalid && "invalid designator has no subobject type")(static_cast <bool> (!Invalid && "invalid designator has no subobject type"
) ? void (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\""
, "clang/lib/AST/ExprConstant.cpp", 384, __extension__ __PRETTY_FUNCTION__
))
;
385 return MostDerivedPathLength == Entries.size()
386 ? MostDerivedType
387 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388 }
389
390 /// Update this designator to refer to the first element within this array.
391 void addArrayUnchecked(const ConstantArrayType *CAT) {
392 Entries.push_back(PathEntry::ArrayIndex(0));
393
394 // This is a most-derived object.
395 MostDerivedType = CAT->getElementType();
396 MostDerivedIsArrayElement = true;
397 MostDerivedArraySize = CAT->getSize().getZExtValue();
398 MostDerivedPathLength = Entries.size();
399 }
400 /// Update this designator to refer to the first element within the array of
401 /// elements of type T. This is an array of unknown size.
402 void addUnsizedArrayUnchecked(QualType ElemTy) {
403 Entries.push_back(PathEntry::ArrayIndex(0));
404
405 MostDerivedType = ElemTy;
406 MostDerivedIsArrayElement = true;
407 // The value in MostDerivedArraySize is undefined in this case. So, set it
408 // to an arbitrary value that's likely to loudly break things if it's
409 // used.
410 MostDerivedArraySize = AssumedSizeForUnsizedArray;
411 MostDerivedPathLength = Entries.size();
412 }
413 /// Update this designator to refer to the given base or member of this
414 /// object.
415 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417
418 // If this isn't a base class, it's a new most-derived object.
419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420 MostDerivedType = FD->getType();
421 MostDerivedIsArrayElement = false;
422 MostDerivedArraySize = 0;
423 MostDerivedPathLength = Entries.size();
424 }
425 }
426 /// Update this designator to refer to the given complex component.
427 void addComplexUnchecked(QualType EltTy, bool Imag) {
428 Entries.push_back(PathEntry::ArrayIndex(Imag));
429
430 // This is technically a most-derived object, though in practice this
431 // is unlikely to matter.
432 MostDerivedType = EltTy;
433 MostDerivedIsArrayElement = true;
434 MostDerivedArraySize = 2;
435 MostDerivedPathLength = Entries.size();
436 }
437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439 const APSInt &N);
440 /// Add N to the address of this subobject.
441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442 if (Invalid || !N) return;
443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444 if (isMostDerivedAnUnsizedArray()) {
445 diagnoseUnsizedArrayPointerArithmetic(Info, E);
446 // Can't verify -- trust that the user is doing the right thing (or if
447 // not, trust that the caller will catch the bad behavior).
448 // FIXME: Should we reject if this overflows, at least?
449 Entries.back() = PathEntry::ArrayIndex(
450 Entries.back().getAsArrayIndex() + TruncatedN);
451 return;
452 }
453
454 // [expr.add]p4: For the purposes of these operators, a pointer to a
455 // nonarray object behaves the same as a pointer to the first element of
456 // an array of length one with the type of the object as its element type.
457 bool IsArray = MostDerivedPathLength == Entries.size() &&
458 MostDerivedIsArrayElement;
459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460 : (uint64_t)IsOnePastTheEnd;
461 uint64_t ArraySize =
462 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463
464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465 // Calculate the actual index in a wide enough type, so we can include
466 // it in the note.
467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468 (llvm::APInt&)N += ArrayIndex;
469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index"
) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 469, __extension__ __PRETTY_FUNCTION__
))
;
470 diagnosePointerArithmetic(Info, E, N);
471 setInvalid();
472 return;
473 }
474
475 ArrayIndex += TruncatedN;
476 assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
477 "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
;
478
479 if (IsArray)
480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481 else
482 IsOnePastTheEnd = (ArrayIndex != 0);
483 }
484 };
485
486 /// A scope at the end of which an object can need to be destroyed.
487 enum class ScopeKind {
488 Block,
489 FullExpression,
490 Call
491 };
492
493 /// A reference to a particular call and its arguments.
494 struct CallRef {
495 CallRef() : OrigCallee(), CallIndex(0), Version() {}
496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498
499 explicit operator bool() const { return OrigCallee; }
500
501 /// Get the parameter that the caller initialized, corresponding to the
502 /// given parameter in the callee.
503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505 : PVD;
506 }
507
508 /// The callee at the point where the arguments were evaluated. This might
509 /// be different from the actual callee (a different redeclaration, or a
510 /// virtual override), but this function's parameters are the ones that
511 /// appear in the parameter map.
512 const FunctionDecl *OrigCallee;
513 /// The call index of the frame that holds the argument values.
514 unsigned CallIndex;
515 /// The version of the parameters corresponding to this call.
516 unsigned Version;
517 };
518
519 /// A stack frame in the constexpr call stack.
520 class CallStackFrame : public interp::Frame {
521 public:
522 EvalInfo &Info;
523
524 /// Parent - The caller of this stack frame.
525 CallStackFrame *Caller;
526
527 /// Callee - The function which was called.
528 const FunctionDecl *Callee;
529
530 /// This - The binding for the this pointer in this call, if any.
531 const LValue *This;
532
533 /// Information on how to find the arguments to this call. Our arguments
534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535 /// key and this value as the version.
536 CallRef Arguments;
537
538 /// Source location information about the default argument or default
539 /// initializer expression we're evaluating, if any.
540 CurrentSourceLocExprScope CurSourceLocExprScope;
541
542 // Note that we intentionally use std::map here so that references to
543 // values are stable.
544 typedef std::pair<const void *, unsigned> MapKeyTy;
545 typedef std::map<MapKeyTy, APValue> MapTy;
546 /// Temporaries - Temporary lvalues materialized within this stack frame.
547 MapTy Temporaries;
548
549 /// CallLoc - The location of the call expression for this call.
550 SourceLocation CallLoc;
551
552 /// Index - The call index of this call.
553 unsigned Index;
554
555 /// The stack of integers for tracking version numbers for temporaries.
556 SmallVector<unsigned, 2> TempVersionStack = {1};
557 unsigned CurTempVersion = TempVersionStack.back();
558
559 unsigned getTempVersion() const { return TempVersionStack.back(); }
560
561 void pushTempVersion() {
562 TempVersionStack.push_back(++CurTempVersion);
563 }
564
565 void popTempVersion() {
566 TempVersionStack.pop_back();
567 }
568
569 CallRef createCall(const FunctionDecl *Callee) {
570 return {Callee, Index, ++CurTempVersion};
571 }
572
573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574 // on the overall stack usage of deeply-recursing constexpr evaluations.
575 // (We should cache this map rather than recomputing it repeatedly.)
576 // But let's try this and see how it goes; we can look into caching the map
577 // as a later change.
578
579 /// LambdaCaptureFields - Mapping from captured variables/this to
580 /// corresponding data members in the closure class.
581 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
582 FieldDecl *LambdaThisCaptureField;
583
584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585 const FunctionDecl *Callee, const LValue *This,
586 CallRef Arguments);
587 ~CallStackFrame();
588
589 // Return the temporary for Key whose version number is Version.
590 APValue *getTemporary(const void *Key, unsigned Version) {
591 MapKeyTy KV(Key, Version);
592 auto LB = Temporaries.lower_bound(KV);
593 if (LB != Temporaries.end() && LB->first == KV)
594 return &LB->second;
595 return nullptr;
596 }
597
598 // Return the current temporary for Key in the map.
599 APValue *getCurrentTemporary(const void *Key) {
600 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
601 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
602 return &std::prev(UB)->second;
603 return nullptr;
604 }
605
606 // Return the version number of the current temporary for Key.
607 unsigned getCurrentTemporaryVersion(const void *Key) const {
608 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
609 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
610 return std::prev(UB)->first.second;
611 return 0;
612 }
613
614 /// Allocate storage for an object of type T in this stack frame.
615 /// Populates LV with a handle to the created object. Key identifies
616 /// the temporary within the stack frame, and must not be reused without
617 /// bumping the temporary version number.
618 template<typename KeyT>
619 APValue &createTemporary(const KeyT *Key, QualType T,
620 ScopeKind Scope, LValue &LV);
621
622 /// Allocate storage for a parameter of a function call made in this frame.
623 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
624
625 void describe(llvm::raw_ostream &OS) override;
626
627 Frame *getCaller() const override { return Caller; }
628 SourceLocation getCallLocation() const override { return CallLoc; }
629 const FunctionDecl *getCallee() const override { return Callee; }
630
631 bool isStdFunction() const {
632 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
633 if (DC->isStdNamespace())
634 return true;
635 return false;
636 }
637
638 private:
639 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
640 ScopeKind Scope);
641 };
642
643 /// Temporarily override 'this'.
644 class ThisOverrideRAII {
645 public:
646 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
647 : Frame(Frame), OldThis(Frame.This) {
648 if (Enable)
649 Frame.This = NewThis;
650 }
651 ~ThisOverrideRAII() {
652 Frame.This = OldThis;
653 }
654 private:
655 CallStackFrame &Frame;
656 const LValue *OldThis;
657 };
658
659 // A shorthand time trace scope struct, prints source range, for example
660 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
661 class ExprTimeTraceScope {
662 public:
663 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
664 : TimeScope(Name, [E, &Ctx] {
665 return E->getSourceRange().printToString(Ctx.getSourceManager());
666 }) {}
667
668 private:
669 llvm::TimeTraceScope TimeScope;
670 };
671}
672
673static bool HandleDestruction(EvalInfo &Info, const Expr *E,
674 const LValue &This, QualType ThisType);
675static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
676 APValue::LValueBase LVBase, APValue &Value,
677 QualType T);
678
679namespace {
680 /// A cleanup, and a flag indicating whether it is lifetime-extended.
681 class Cleanup {
682 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
683 APValue::LValueBase Base;
684 QualType T;
685
686 public:
687 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
688 ScopeKind Scope)
689 : Value(Val, Scope), Base(Base), T(T) {}
690
691 /// Determine whether this cleanup should be performed at the end of the
692 /// given kind of scope.
693 bool isDestroyedAtEndOf(ScopeKind K) const {
694 return (int)Value.getInt() >= (int)K;
695 }
696 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
697 if (RunDestructors) {
698 SourceLocation Loc;
699 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
700 Loc = VD->getLocation();
701 else if (const Expr *E = Base.dyn_cast<const Expr*>())
702 Loc = E->getExprLoc();
703 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
704 }
705 *Value.getPointer() = APValue();
706 return true;
707 }
708
709 bool hasSideEffect() {
710 return T.isDestructedType();
711 }
712 };
713
714 /// A reference to an object whose construction we are currently evaluating.
715 struct ObjectUnderConstruction {
716 APValue::LValueBase Base;
717 ArrayRef<APValue::LValuePathEntry> Path;
718 friend bool operator==(const ObjectUnderConstruction &LHS,
719 const ObjectUnderConstruction &RHS) {
720 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
721 }
722 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
723 return llvm::hash_combine(Obj.Base, Obj.Path);
724 }
725 };
726 enum class ConstructionPhase {
727 None,
728 Bases,
729 AfterBases,
730 AfterFields,
731 Destroying,
732 DestroyingBases
733 };
734}
735
736namespace llvm {
737template<> struct DenseMapInfo<ObjectUnderConstruction> {
738 using Base = DenseMapInfo<APValue::LValueBase>;
739 static ObjectUnderConstruction getEmptyKey() {
740 return {Base::getEmptyKey(), {}}; }
741 static ObjectUnderConstruction getTombstoneKey() {
742 return {Base::getTombstoneKey(), {}};
743 }
744 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
745 return hash_value(Object);
746 }
747 static bool isEqual(const ObjectUnderConstruction &LHS,
748 const ObjectUnderConstruction &RHS) {
749 return LHS == RHS;
750 }
751};
752}
753
754namespace {
755 /// A dynamically-allocated heap object.
756 struct DynAlloc {
757 /// The value of this heap-allocated object.
758 APValue Value;
759 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
760 /// or a CallExpr (the latter is for direct calls to operator new inside
761 /// std::allocator<T>::allocate).
762 const Expr *AllocExpr = nullptr;
763
764 enum Kind {
765 New,
766 ArrayNew,
767 StdAllocator
768 };
769
770 /// Get the kind of the allocation. This must match between allocation
771 /// and deallocation.
772 Kind getKind() const {
773 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
774 return NE->isArray() ? ArrayNew : New;
775 assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void
(0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "clang/lib/AST/ExprConstant.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
;
776 return StdAllocator;
777 }
778 };
779
780 struct DynAllocOrder {
781 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
782 return L.getIndex() < R.getIndex();
783 }
784 };
785
786 /// EvalInfo - This is a private struct used by the evaluator to capture
787 /// information about a subexpression as it is folded. It retains information
788 /// about the AST context, but also maintains information about the folded
789 /// expression.
790 ///
791 /// If an expression could be evaluated, it is still possible it is not a C
792 /// "integer constant expression" or constant expression. If not, this struct
793 /// captures information about how and why not.
794 ///
795 /// One bit of information passed *into* the request for constant folding
796 /// indicates whether the subexpression is "evaluated" or not according to C
797 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
798 /// evaluate the expression regardless of what the RHS is, but C only allows
799 /// certain things in certain situations.
800 class EvalInfo : public interp::State {
801 public:
802 ASTContext &Ctx;
803
804 /// EvalStatus - Contains information about the evaluation.
805 Expr::EvalStatus &EvalStatus;
806
807 /// CurrentCall - The top of the constexpr call stack.
808 CallStackFrame *CurrentCall;
809
810 /// CallStackDepth - The number of calls in the call stack right now.
811 unsigned CallStackDepth;
812
813 /// NextCallIndex - The next call index to assign.
814 unsigned NextCallIndex;
815
816 /// StepsLeft - The remaining number of evaluation steps we're permitted
817 /// to perform. This is essentially a limit for the number of statements
818 /// we will evaluate.
819 unsigned StepsLeft;
820
821 /// Enable the experimental new constant interpreter. If an expression is
822 /// not supported by the interpreter, an error is triggered.
823 bool EnableNewConstInterp;
824
825 /// BottomFrame - The frame in which evaluation started. This must be
826 /// initialized after CurrentCall and CallStackDepth.
827 CallStackFrame BottomFrame;
828
829 /// A stack of values whose lifetimes end at the end of some surrounding
830 /// evaluation frame.
831 llvm::SmallVector<Cleanup, 16> CleanupStack;
832
833 /// EvaluatingDecl - This is the declaration whose initializer is being
834 /// evaluated, if any.
835 APValue::LValueBase EvaluatingDecl;
836
837 enum class EvaluatingDeclKind {
838 None,
839 /// We're evaluating the construction of EvaluatingDecl.
840 Ctor,
841 /// We're evaluating the destruction of EvaluatingDecl.
842 Dtor,
843 };
844 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
845
846 /// EvaluatingDeclValue - This is the value being constructed for the
847 /// declaration whose initializer is being evaluated, if any.
848 APValue *EvaluatingDeclValue;
849
850 /// Set of objects that are currently being constructed.
851 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
852 ObjectsUnderConstruction;
853
854 /// Current heap allocations, along with the location where each was
855 /// allocated. We use std::map here because we need stable addresses
856 /// for the stored APValues.
857 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
858
859 /// The number of heap allocations performed so far in this evaluation.
860 unsigned NumHeapAllocs = 0;
861
862 struct EvaluatingConstructorRAII {
863 EvalInfo &EI;
864 ObjectUnderConstruction Object;
865 bool DidInsert;
866 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
867 bool HasBases)
868 : EI(EI), Object(Object) {
869 DidInsert =
870 EI.ObjectsUnderConstruction
871 .insert({Object, HasBases ? ConstructionPhase::Bases
872 : ConstructionPhase::AfterBases})
873 .second;
874 }
875 void finishedConstructingBases() {
876 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
877 }
878 void finishedConstructingFields() {
879 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
880 }
881 ~EvaluatingConstructorRAII() {
882 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
883 }
884 };
885
886 struct EvaluatingDestructorRAII {
887 EvalInfo &EI;
888 ObjectUnderConstruction Object;
889 bool DidInsert;
890 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
891 : EI(EI), Object(Object) {
892 DidInsert = EI.ObjectsUnderConstruction
893 .insert({Object, ConstructionPhase::Destroying})
894 .second;
895 }
896 void startedDestroyingBases() {
897 EI.ObjectsUnderConstruction[Object] =
898 ConstructionPhase::DestroyingBases;
899 }
900 ~EvaluatingDestructorRAII() {
901 if (DidInsert)
902 EI.ObjectsUnderConstruction.erase(Object);
903 }
904 };
905
906 ConstructionPhase
907 isEvaluatingCtorDtor(APValue::LValueBase Base,
908 ArrayRef<APValue::LValuePathEntry> Path) {
909 return ObjectsUnderConstruction.lookup({Base, Path});
910 }
911
912 /// If we're currently speculatively evaluating, the outermost call stack
913 /// depth at which we can mutate state, otherwise 0.
914 unsigned SpeculativeEvaluationDepth = 0;
915
916 /// The current array initialization index, if we're performing array
917 /// initialization.
918 uint64_t ArrayInitIndex = -1;
919
920 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
921 /// notes attached to it will also be stored, otherwise they will not be.
922 bool HasActiveDiagnostic;
923
924 /// Have we emitted a diagnostic explaining why we couldn't constant
925 /// fold (not just why it's not strictly a constant expression)?
926 bool HasFoldFailureDiagnostic;
927
928 /// Whether we're checking that an expression is a potential constant
929 /// expression. If so, do not fail on constructs that could become constant
930 /// later on (such as a use of an undefined global).
931 bool CheckingPotentialConstantExpression = false;
932
933 /// Whether we're checking for an expression that has undefined behavior.
934 /// If so, we will produce warnings if we encounter an operation that is
935 /// always undefined.
936 ///
937 /// Note that we still need to evaluate the expression normally when this
938 /// is set; this is used when evaluating ICEs in C.
939 bool CheckingForUndefinedBehavior = false;
940
941 enum EvaluationMode {
942 /// Evaluate as a constant expression. Stop if we find that the expression
943 /// is not a constant expression.
944 EM_ConstantExpression,
945
946 /// Evaluate as a constant expression. Stop if we find that the expression
947 /// is not a constant expression. Some expressions can be retried in the
948 /// optimizer if we don't constant fold them here, but in an unevaluated
949 /// context we try to fold them immediately since the optimizer never
950 /// gets a chance to look at it.
951 EM_ConstantExpressionUnevaluated,
952
953 /// Fold the expression to a constant. Stop if we hit a side-effect that
954 /// we can't model.
955 EM_ConstantFold,
956
957 /// Evaluate in any way we know how. Don't worry about side-effects that
958 /// can't be modeled.
959 EM_IgnoreSideEffects,
960 } EvalMode;
961
962 /// Are we checking whether the expression is a potential constant
963 /// expression?
964 bool checkingPotentialConstantExpression() const override {
965 return CheckingPotentialConstantExpression;
966 }
967
968 /// Are we checking an expression for overflow?
969 // FIXME: We should check for any kind of undefined or suspicious behavior
970 // in such constructs, not just overflow.
971 bool checkingForUndefinedBehavior() const override {
972 return CheckingForUndefinedBehavior;
973 }
974
975 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977 CallStackDepth(0), NextCallIndex(1),
978 StepsLeft(C.getLangOpts().ConstexprStepLimit),
979 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981 EvaluatingDecl((const ValueDecl *)nullptr),
982 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
984
985 ~EvalInfo() {
986 discardCleanups();
987 }
988
989 ASTContext &getCtx() const override { return Ctx; }
990
991 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
992 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
993 EvaluatingDecl = Base;
994 IsEvaluatingDecl = EDK;
995 EvaluatingDeclValue = &Value;
996 }
997
998 bool CheckCallLimit(SourceLocation Loc) {
999 // Don't perform any constexpr calls (other than the call we're checking)
1000 // when checking a potential constant expression.
1001 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1002 return false;
1003 if (NextCallIndex == 0) {
1004 // NextCallIndex has wrapped around.
1005 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1006 return false;
1007 }
1008 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1009 return true;
1010 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1011 << getLangOpts().ConstexprCallDepth;
1012 return false;
1013 }
1014
1015 std::pair<CallStackFrame *, unsigned>
1016 getCallFrameAndDepth(unsigned CallIndex) {
1017 assert(CallIndex && "no call index in getCallFrameAndDepth")(static_cast <bool> (CallIndex && "no call index in getCallFrameAndDepth"
) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\""
, "clang/lib/AST/ExprConstant.cpp", 1017, __extension__ __PRETTY_FUNCTION__
))
;
1018 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1019 // be null in this loop.
1020 unsigned Depth = CallStackDepth;
1021 CallStackFrame *Frame = CurrentCall;
1022 while (Frame->Index > CallIndex) {
1023 Frame = Frame->Caller;
1024 --Depth;
1025 }
1026 if (Frame->Index == CallIndex)
1027 return {Frame, Depth};
1028 return {nullptr, 0};
1029 }
1030
1031 bool nextStep(const Stmt *S) {
1032 if (!StepsLeft) {
1033 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1034 return false;
1035 }
1036 --StepsLeft;
1037 return true;
1038 }
1039
1040 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1041
1042 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1043 std::optional<DynAlloc *> Result;
1044 auto It = HeapAllocs.find(DA);
1045 if (It != HeapAllocs.end())
1046 Result = &It->second;
1047 return Result;
1048 }
1049
1050 /// Get the allocated storage for the given parameter of the given call.
1051 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1052 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1053 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1054 : nullptr;
1055 }
1056
1057 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1058 struct StdAllocatorCaller {
1059 unsigned FrameIndex;
1060 QualType ElemType;
1061 explicit operator bool() const { return FrameIndex != 0; };
1062 };
1063
1064 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1065 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1066 Call = Call->Caller) {
1067 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1068 if (!MD)
1069 continue;
1070 const IdentifierInfo *FnII = MD->getIdentifier();
1071 if (!FnII || !FnII->isStr(FnName))
1072 continue;
1073
1074 const auto *CTSD =
1075 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1076 if (!CTSD)
1077 continue;
1078
1079 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1080 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1081 if (CTSD->isInStdNamespace() && ClassII &&
1082 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1083 TAL[0].getKind() == TemplateArgument::Type)
1084 return {Call->Index, TAL[0].getAsType()};
1085 }
1086
1087 return {};
1088 }
1089
1090 void performLifetimeExtension() {
1091 // Disable the cleanups for lifetime-extended temporaries.
1092 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1093 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1094 });
1095 }
1096
1097 /// Throw away any remaining cleanups at the end of evaluation. If any
1098 /// cleanups would have had a side-effect, note that as an unmodeled
1099 /// side-effect and return false. Otherwise, return true.
1100 bool discardCleanups() {
1101 for (Cleanup &C : CleanupStack) {
1102 if (C.hasSideEffect() && !noteSideEffect()) {
1103 CleanupStack.clear();
1104 return false;
1105 }
1106 }
1107 CleanupStack.clear();
1108 return true;
1109 }
1110
1111 private:
1112 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1113 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1114
1115 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1116 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1117
1118 void setFoldFailureDiagnostic(bool Flag) override {
1119 HasFoldFailureDiagnostic = Flag;
1120 }
1121
1122 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1123
1124 // If we have a prior diagnostic, it will be noting that the expression
1125 // isn't a constant expression. This diagnostic is more important,
1126 // unless we require this evaluation to produce a constant expression.
1127 //
1128 // FIXME: We might want to show both diagnostics to the user in
1129 // EM_ConstantFold mode.
1130 bool hasPriorDiagnostic() override {
1131 if (!EvalStatus.Diag->empty()) {
1132 switch (EvalMode) {
1133 case EM_ConstantFold:
1134 case EM_IgnoreSideEffects:
1135 if (!HasFoldFailureDiagnostic)
1136 break;
1137 // We've already failed to fold something. Keep that diagnostic.
1138 [[fallthrough]];
1139 case EM_ConstantExpression:
1140 case EM_ConstantExpressionUnevaluated:
1141 setActiveDiagnostic(false);
1142 return true;
1143 }
1144 }
1145 return false;
1146 }
1147
1148 unsigned getCallStackDepth() override { return CallStackDepth; }
1149
1150 public:
1151 /// Should we continue evaluation after encountering a side-effect that we
1152 /// couldn't model?
1153 bool keepEvaluatingAfterSideEffect() {
1154 switch (EvalMode) {
1155 case EM_IgnoreSideEffects:
1156 return true;
1157
1158 case EM_ConstantExpression:
1159 case EM_ConstantExpressionUnevaluated:
1160 case EM_ConstantFold:
1161 // By default, assume any side effect might be valid in some other
1162 // evaluation of this expression from a different context.
1163 return checkingPotentialConstantExpression() ||
1164 checkingForUndefinedBehavior();
1165 }
1166 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1166)
;
1167 }
1168
1169 /// Note that we have had a side-effect, and determine whether we should
1170 /// keep evaluating.
1171 bool noteSideEffect() {
1172 EvalStatus.HasSideEffects = true;
1173 return keepEvaluatingAfterSideEffect();
1174 }
1175
1176 /// Should we continue evaluation after encountering undefined behavior?
1177 bool keepEvaluatingAfterUndefinedBehavior() {
1178 switch (EvalMode) {
1179 case EM_IgnoreSideEffects:
1180 case EM_ConstantFold:
1181 return true;
1182
1183 case EM_ConstantExpression:
1184 case EM_ConstantExpressionUnevaluated:
1185 return checkingForUndefinedBehavior();
1186 }
1187 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1187)
;
1188 }
1189
1190 /// Note that we hit something that was technically undefined behavior, but
1191 /// that we can evaluate past it (such as signed overflow or floating-point
1192 /// division by zero.)
1193 bool noteUndefinedBehavior() override {
1194 EvalStatus.HasUndefinedBehavior = true;
1195 return keepEvaluatingAfterUndefinedBehavior();
1196 }
1197
1198 /// Should we continue evaluation as much as possible after encountering a
1199 /// construct which can't be reduced to a value?
1200 bool keepEvaluatingAfterFailure() const override {
1201 if (!StepsLeft)
1202 return false;
1203
1204 switch (EvalMode) {
1205 case EM_ConstantExpression:
1206 case EM_ConstantExpressionUnevaluated:
1207 case EM_ConstantFold:
1208 case EM_IgnoreSideEffects:
1209 return checkingPotentialConstantExpression() ||
1210 checkingForUndefinedBehavior();
1211 }
1212 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1212)
;
1213 }
1214
1215 /// Notes that we failed to evaluate an expression that other expressions
1216 /// directly depend on, and determine if we should keep evaluating. This
1217 /// should only be called if we actually intend to keep evaluating.
1218 ///
1219 /// Call noteSideEffect() instead if we may be able to ignore the value that
1220 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1221 ///
1222 /// (Foo(), 1) // use noteSideEffect
1223 /// (Foo() || true) // use noteSideEffect
1224 /// Foo() + 1 // use noteFailure
1225 [[nodiscard]] bool noteFailure() {
1226 // Failure when evaluating some expression often means there is some
1227 // subexpression whose evaluation was skipped. Therefore, (because we
1228 // don't track whether we skipped an expression when unwinding after an
1229 // evaluation failure) every evaluation failure that bubbles up from a
1230 // subexpression implies that a side-effect has potentially happened. We
1231 // skip setting the HasSideEffects flag to true until we decide to
1232 // continue evaluating after that point, which happens here.
1233 bool KeepGoing = keepEvaluatingAfterFailure();
1234 EvalStatus.HasSideEffects |= KeepGoing;
1235 return KeepGoing;
1236 }
1237
1238 class ArrayInitLoopIndex {
1239 EvalInfo &Info;
1240 uint64_t OuterIndex;
1241
1242 public:
1243 ArrayInitLoopIndex(EvalInfo &Info)
1244 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1245 Info.ArrayInitIndex = 0;
1246 }
1247 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1248
1249 operator uint64_t&() { return Info.ArrayInitIndex; }
1250 };
1251 };
1252
1253 /// Object used to treat all foldable expressions as constant expressions.
1254 struct FoldConstant {
1255 EvalInfo &Info;
1256 bool Enabled;
1257 bool HadNoPriorDiags;
1258 EvalInfo::EvaluationMode OldMode;
1259
1260 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1261 : Info(Info),
1262 Enabled(Enabled),
1263 HadNoPriorDiags(Info.EvalStatus.Diag &&
1264 Info.EvalStatus.Diag->empty() &&
1265 !Info.EvalStatus.HasSideEffects),
1266 OldMode(Info.EvalMode) {
1267 if (Enabled)
1268 Info.EvalMode = EvalInfo::EM_ConstantFold;
1269 }
1270 void keepDiagnostics() { Enabled = false; }
1271 ~FoldConstant() {
1272 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1273 !Info.EvalStatus.HasSideEffects)
1274 Info.EvalStatus.Diag->clear();
1275 Info.EvalMode = OldMode;
1276 }
1277 };
1278
1279 /// RAII object used to set the current evaluation mode to ignore
1280 /// side-effects.
1281 struct IgnoreSideEffectsRAII {
1282 EvalInfo &Info;
1283 EvalInfo::EvaluationMode OldMode;
1284 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1285 : Info(Info), OldMode(Info.EvalMode) {
1286 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1287 }
1288
1289 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1290 };
1291
1292 /// RAII object used to optionally suppress diagnostics and side-effects from
1293 /// a speculative evaluation.
1294 class SpeculativeEvaluationRAII {
1295 EvalInfo *Info = nullptr;
1296 Expr::EvalStatus OldStatus;
1297 unsigned OldSpeculativeEvaluationDepth;
1298
1299 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1300 Info = Other.Info;
1301 OldStatus = Other.OldStatus;
1302 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1303 Other.Info = nullptr;
1304 }
1305
1306 void maybeRestoreState() {
1307 if (!Info)
1308 return;
1309
1310 Info->EvalStatus = OldStatus;
1311 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1312 }
1313
1314 public:
1315 SpeculativeEvaluationRAII() = default;
1316
1317 SpeculativeEvaluationRAII(
1318 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1319 : Info(&Info), OldStatus(Info.EvalStatus),
1320 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1321 Info.EvalStatus.Diag = NewDiag;
1322 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1323 }
1324
1325 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1326 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1327 moveFromAndCancel(std::move(Other));
1328 }
1329
1330 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1331 maybeRestoreState();
1332 moveFromAndCancel(std::move(Other));
1333 return *this;
1334 }
1335
1336 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1337 };
1338
1339 /// RAII object wrapping a full-expression or block scope, and handling
1340 /// the ending of the lifetime of temporaries created within it.
1341 template<ScopeKind Kind>
1342 class ScopeRAII {
1343 EvalInfo &Info;
1344 unsigned OldStackSize;
1345 public:
1346 ScopeRAII(EvalInfo &Info)
1347 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1348 // Push a new temporary version. This is needed to distinguish between
1349 // temporaries created in different iterations of a loop.
1350 Info.CurrentCall->pushTempVersion();
1351 }
1352 bool destroy(bool RunDestructors = true) {
1353 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1354 OldStackSize = -1U;
1355 return OK;
1356 }
1357 ~ScopeRAII() {
1358 if (OldStackSize != -1U)
1359 destroy(false);
1360 // Body moved to a static method to encourage the compiler to inline away
1361 // instances of this class.
1362 Info.CurrentCall->popTempVersion();
1363 }
1364 private:
1365 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1366 unsigned OldStackSize) {
1367 assert(OldStackSize <= Info.CleanupStack.size() &&(static_cast <bool> (OldStackSize <= Info.CleanupStack
.size() && "running cleanups out of order?") ? void (
0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "clang/lib/AST/ExprConstant.cpp", 1368, __extension__ __PRETTY_FUNCTION__
))
1368 "running cleanups out of order?")(static_cast <bool> (OldStackSize <= Info.CleanupStack
.size() && "running cleanups out of order?") ? void (
0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "clang/lib/AST/ExprConstant.cpp", 1368, __extension__ __PRETTY_FUNCTION__
))
;
1369
1370 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1371 // for a full-expression scope.
1372 bool Success = true;
1373 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1374 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1375 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1376 Success = false;
1377 break;
1378 }
1379 }
1380 }
1381
1382 // Compact any retained cleanups.
1383 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1384 if (Kind != ScopeKind::Block)
1385 NewEnd =
1386 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1387 return C.isDestroyedAtEndOf(Kind);
1388 });
1389 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1390 return Success;
1391 }
1392 };
1393 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1394 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1395 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1396}
1397
1398bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1399 CheckSubobjectKind CSK) {
1400 if (Invalid)
1401 return false;
1402 if (isOnePastTheEnd()) {
1403 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1404 << CSK;
1405 setInvalid();
1406 return false;
1407 }
1408 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1409 // must actually be at least one array element; even a VLA cannot have a
1410 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1411 return true;
1412}
1413
1414void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1415 const Expr *E) {
1416 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1417 // Do not set the designator as invalid: we can represent this situation,
1418 // and correct handling of __builtin_object_size requires us to do so.
1419}
1420
1421void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1422 const Expr *E,
1423 const APSInt &N) {
1424 // If we're complaining, we must be able to statically determine the size of
1425 // the most derived array.
1426 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1427 Info.CCEDiag(E, diag::note_constexpr_array_index)
1428 << N << /*array*/ 0
1429 << static_cast<unsigned>(getMostDerivedArraySize());
1430 else
1431 Info.CCEDiag(E, diag::note_constexpr_array_index)
1432 << N << /*non-array*/ 1;
1433 setInvalid();
1434}
1435
1436CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1437 const FunctionDecl *Callee, const LValue *This,
1438 CallRef Call)
1439 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1440 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1441 Info.CurrentCall = this;
1442 ++Info.CallStackDepth;
1443}
1444
1445CallStackFrame::~CallStackFrame() {
1446 assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this &&
"calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\""
, "clang/lib/AST/ExprConstant.cpp", 1446, __extension__ __PRETTY_FUNCTION__
))
;
1447 --Info.CallStackDepth;
1448 Info.CurrentCall = Caller;
1449}
1450
1451static bool isRead(AccessKinds AK) {
1452 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1453}
1454
1455static bool isModification(AccessKinds AK) {
1456 switch (AK) {
1457 case AK_Read:
1458 case AK_ReadObjectRepresentation:
1459 case AK_MemberCall:
1460 case AK_DynamicCast:
1461 case AK_TypeId:
1462 return false;
1463 case AK_Assign:
1464 case AK_Increment:
1465 case AK_Decrement:
1466 case AK_Construct:
1467 case AK_Destroy:
1468 return true;
1469 }
1470 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1470)
;
1471}
1472
1473static bool isAnyAccess(AccessKinds AK) {
1474 return isRead(AK) || isModification(AK);
1475}
1476
1477/// Is this an access per the C++ definition?
1478static bool isFormalAccess(AccessKinds AK) {
1479 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1480}
1481
1482/// Is this kind of axcess valid on an indeterminate object value?
1483static bool isValidIndeterminateAccess(AccessKinds AK) {
1484 switch (AK) {
1485 case AK_Read:
1486 case AK_Increment:
1487 case AK_Decrement:
1488 // These need the object's value.
1489 return false;
1490
1491 case AK_ReadObjectRepresentation:
1492 case AK_Assign:
1493 case AK_Construct:
1494 case AK_Destroy:
1495 // Construction and destruction don't need the value.
1496 return true;
1497
1498 case AK_MemberCall:
1499 case AK_DynamicCast:
1500 case AK_TypeId:
1501 // These aren't really meaningful on scalars.
1502 return true;
1503 }
1504 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1504)
;
1505}
1506
1507namespace {
1508 struct ComplexValue {
1509 private:
1510 bool IsInt;
1511
1512 public:
1513 APSInt IntReal, IntImag;
1514 APFloat FloatReal, FloatImag;
1515
1516 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517
1518 void makeComplexFloat() { IsInt = false; }
1519 bool isComplexFloat() const { return !IsInt; }
1520 APFloat &getComplexFloatReal() { return FloatReal; }
1521 APFloat &getComplexFloatImag() { return FloatImag; }
1522
1523 void makeComplexInt() { IsInt = true; }
1524 bool isComplexInt() const { return IsInt; }
1525 APSInt &getComplexIntReal() { return IntReal; }
1526 APSInt &getComplexIntImag() { return IntImag; }
1527
1528 void moveInto(APValue &v) const {
1529 if (isComplexFloat())
1530 v = APValue(FloatReal, FloatImag);
1531 else
1532 v = APValue(IntReal, IntImag);
1533 }
1534 void setFrom(const APValue &v) {
1535 assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt
()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "clang/lib/AST/ExprConstant.cpp", 1535, __extension__ __PRETTY_FUNCTION__
))
;
1536 if (v.isComplexFloat()) {
1537 makeComplexFloat();
1538 FloatReal = v.getComplexFloatReal();
1539 FloatImag = v.getComplexFloatImag();
1540 } else {
1541 makeComplexInt();
1542 IntReal = v.getComplexIntReal();
1543 IntImag = v.getComplexIntImag();
1544 }
1545 }
1546 };
1547
1548 struct LValue {
1549 APValue::LValueBase Base;
1550 CharUnits Offset;
1551 SubobjectDesignator Designator;
1552 bool IsNullPtr : 1;
1553 bool InvalidBase : 1;
1554
1555 const APValue::LValueBase getLValueBase() const { return Base; }
1556 CharUnits &getLValueOffset() { return Offset; }
1557 const CharUnits &getLValueOffset() const { return Offset; }
1558 SubobjectDesignator &getLValueDesignator() { return Designator; }
1559 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1560 bool isNullPointer() const { return IsNullPtr;}
1561
1562 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1563 unsigned getLValueVersion() const { return Base.getVersion(); }
1564
1565 void moveInto(APValue &V) const {
1566 if (Designator.Invalid)
1567 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1568 else {
1569 assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases"
) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\""
, "clang/lib/AST/ExprConstant.cpp", 1569, __extension__ __PRETTY_FUNCTION__
))
;
1570 V = APValue(Base, Offset, Designator.Entries,
1571 Designator.IsOnePastTheEnd, IsNullPtr);
1572 }
1573 }
1574 void setFrom(ASTContext &Ctx, const APValue &V) {
1575 assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\""
, "clang/lib/AST/ExprConstant.cpp", 1575, __extension__ __PRETTY_FUNCTION__
))
;
1576 Base = V.getLValueBase();
1577 Offset = V.getLValueOffset();
1578 InvalidBase = false;
1579 Designator = SubobjectDesignator(Ctx, V);
1580 IsNullPtr = V.isNullPointer();
1581 }
1582
1583 void set(APValue::LValueBase B, bool BInvalid = false) {
1584#ifndef NDEBUG
1585 // We only allow a few types of invalid bases. Enforce that here.
1586 if (BInvalid) {
1587 const auto *E = B.get<const Expr *>();
1588 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "clang/lib/AST/ExprConstant.cpp", 1589, __extension__ __PRETTY_FUNCTION__
))
1589 "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "clang/lib/AST/ExprConstant.cpp", 1589, __extension__ __PRETTY_FUNCTION__
))
;
1590 }
1591#endif
1592
1593 Base = B;
1594 Offset = CharUnits::fromQuantity(0);
1595 InvalidBase = BInvalid;
1596 Designator = SubobjectDesignator(getType(B));
1597 IsNullPtr = false;
1598 }
1599
1600 void setNull(ASTContext &Ctx, QualType PointerTy) {
1601 Base = (const ValueDecl *)nullptr;
1602 Offset =
1603 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1604 InvalidBase = false;
1605 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1606 IsNullPtr = true;
1607 }
1608
1609 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1610 set(B, true);
1611 }
1612
1613 std::string toString(ASTContext &Ctx, QualType T) const {
1614 APValue Printable;
1615 moveInto(Printable);
1616 return Printable.getAsString(Ctx, T);
1617 }
1618
1619 private:
1620 // Check that this LValue is not based on a null pointer. If it is, produce
1621 // a diagnostic and mark the designator as invalid.
1622 template <typename GenDiagType>
1623 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1624 if (Designator.Invalid)
1625 return false;
1626 if (IsNullPtr) {
1627 GenDiag();
1628 Designator.setInvalid();
1629 return false;
1630 }
1631 return true;
1632 }
1633
1634 public:
1635 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1636 CheckSubobjectKind CSK) {
1637 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1638 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1639 });
1640 }
1641
1642 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1643 AccessKinds AK) {
1644 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1645 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1646 });
1647 }
1648
1649 // Check this LValue refers to an object. If not, set the designator to be
1650 // invalid and emit a diagnostic.
1651 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1652 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1653 Designator.checkSubobject(Info, E, CSK);
1654 }
1655
1656 void addDecl(EvalInfo &Info, const Expr *E,
1657 const Decl *D, bool Virtual = false) {
1658 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1659 Designator.addDeclUnchecked(D, Virtual);
1660 }
1661 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1662 if (!Designator.Entries.empty()) {
1663 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1664 Designator.setInvalid();
1665 return;
1666 }
1667 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1668 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() ||
getType(Base)->isArrayType()) ? void (0) : __assert_fail (
"getType(Base)->isPointerType() || getType(Base)->isArrayType()"
, "clang/lib/AST/ExprConstant.cpp", 1668, __extension__ __PRETTY_FUNCTION__
))
;
1669 Designator.FirstEntryIsAnUnsizedArray = true;
1670 Designator.addUnsizedArrayUnchecked(ElemTy);
1671 }
1672 }
1673 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1674 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1675 Designator.addArrayUnchecked(CAT);
1676 }
1677 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1678 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1679 Designator.addComplexUnchecked(EltTy, Imag);
1680 }
1681 void clearIsNullPointer() {
1682 IsNullPtr = false;
1683 }
1684 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1685 const APSInt &Index, CharUnits ElementSize) {
1686 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1687 // but we're not required to diagnose it and it's valid in C++.)
1688 if (!Index)
1689 return;
1690
1691 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1692 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1693 // offsets.
1694 uint64_t Offset64 = Offset.getQuantity();
1695 uint64_t ElemSize64 = ElementSize.getQuantity();
1696 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1697 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1698
1699 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1700 Designator.adjustIndex(Info, E, Index);
1701 clearIsNullPointer();
1702 }
1703 void adjustOffset(CharUnits N) {
1704 Offset += N;
1705 if (N.getQuantity())
1706 clearIsNullPointer();
1707 }
1708 };
1709
1710 struct MemberPtr {
1711 MemberPtr() {}
1712 explicit MemberPtr(const ValueDecl *Decl)
1713 : DeclAndIsDerivedMember(Decl, false) {}
1714
1715 /// The member or (direct or indirect) field referred to by this member
1716 /// pointer, or 0 if this is a null member pointer.
1717 const ValueDecl *getDecl() const {
1718 return DeclAndIsDerivedMember.getPointer();
1719 }
1720 /// Is this actually a member of some type derived from the relevant class?
1721 bool isDerivedMember() const {
1722 return DeclAndIsDerivedMember.getInt();
1723 }
1724 /// Get the class which the declaration actually lives in.
1725 const CXXRecordDecl *getContainingRecord() const {
1726 return cast<CXXRecordDecl>(
1727 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1728 }
1729
1730 void moveInto(APValue &V) const {
1731 V = APValue(getDecl(), isDerivedMember(), Path);
1732 }
1733 void setFrom(const APValue &V) {
1734 assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail
("V.isMemberPointer()", "clang/lib/AST/ExprConstant.cpp", 1734
, __extension__ __PRETTY_FUNCTION__))
;
1735 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1736 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1737 Path.clear();
1738 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1739 Path.insert(Path.end(), P.begin(), P.end());
1740 }
1741
1742 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1743 /// whether the member is a member of some class derived from the class type
1744 /// of the member pointer.
1745 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1746 /// Path - The path of base/derived classes from the member declaration's
1747 /// class (exclusive) to the class type of the member pointer (inclusive).
1748 SmallVector<const CXXRecordDecl*, 4> Path;
1749
1750 /// Perform a cast towards the class of the Decl (either up or down the
1751 /// hierarchy).
1752 bool castBack(const CXXRecordDecl *Class) {
1753 assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail
("!Path.empty()", "clang/lib/AST/ExprConstant.cpp", 1753, __extension__
__PRETTY_FUNCTION__))
;
1754 const CXXRecordDecl *Expected;
1755 if (Path.size() >= 2)
1756 Expected = Path[Path.size() - 2];
1757 else
1758 Expected = getContainingRecord();
1759 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1760 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1761 // if B does not contain the original member and is not a base or
1762 // derived class of the class containing the original member, the result
1763 // of the cast is undefined.
1764 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1765 // (D::*). We consider that to be a language defect.
1766 return false;
1767 }
1768 Path.pop_back();
1769 return true;
1770 }
1771 /// Perform a base-to-derived member pointer cast.
1772 bool castToDerived(const CXXRecordDecl *Derived) {
1773 if (!getDecl())
1774 return true;
1775 if (!isDerivedMember()) {
1776 Path.push_back(Derived);
1777 return true;
1778 }
1779 if (!castBack(Derived))
1780 return false;
1781 if (Path.empty())
1782 DeclAndIsDerivedMember.setInt(false);
1783 return true;
1784 }
1785 /// Perform a derived-to-base member pointer cast.
1786 bool castToBase(const CXXRecordDecl *Base) {
1787 if (!getDecl())
1788 return true;
1789 if (Path.empty())
1790 DeclAndIsDerivedMember.setInt(true);
1791 if (isDerivedMember()) {
1792 Path.push_back(Base);
1793 return true;
1794 }
1795 return castBack(Base);
1796 }
1797 };
1798
1799 /// Compare two member pointers, which are assumed to be of the same type.
1800 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1801 if (!LHS.getDecl() || !RHS.getDecl())
1802 return !LHS.getDecl() && !RHS.getDecl();
1803 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1804 return false;
1805 return LHS.Path == RHS.Path;
1806 }
1807}
1808
1809static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1810static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1811 const LValue &This, const Expr *E,
1812 bool AllowNonLiteralTypes = false);
1813static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1814 bool InvalidBaseOK = false);
1815static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1816 bool InvalidBaseOK = false);
1817static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1818 EvalInfo &Info);
1819static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1820static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1821static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1822 EvalInfo &Info);
1823static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1824static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1825static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1826 EvalInfo &Info);
1827static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1828static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1829 EvalInfo &Info);
1830
1831/// Evaluate an integer or fixed point expression into an APResult.
1832static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1833 EvalInfo &Info);
1834
1835/// Evaluate only a fixed point expression into an APResult.
1836static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1837 EvalInfo &Info);
1838
1839//===----------------------------------------------------------------------===//
1840// Misc utilities
1841//===----------------------------------------------------------------------===//
1842
1843/// Negate an APSInt in place, converting it to a signed form if necessary, and
1844/// preserving its value (by extending by up to one bit as needed).
1845static void negateAsSigned(APSInt &Int) {
1846 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1847 Int = Int.extend(Int.getBitWidth() + 1);
1848 Int.setIsSigned(true);
1849 }
1850 Int = -Int;
1851}
1852
1853template<typename KeyT>
1854APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1855 ScopeKind Scope, LValue &LV) {
1856 unsigned Version = getTempVersion();
1857 APValue::LValueBase Base(Key, Index, Version);
1858 LV.set(Base);
1859 return createLocal(Base, Key, T, Scope);
1860}
1861
1862/// Allocate storage for a parameter of a function call made in this frame.
1863APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1864 LValue &LV) {
1865 assert(Args.CallIndex == Index && "creating parameter in wrong frame")(static_cast <bool> (Args.CallIndex == Index &&
"creating parameter in wrong frame") ? void (0) : __assert_fail
("Args.CallIndex == Index && \"creating parameter in wrong frame\""
, "clang/lib/AST/ExprConstant.cpp", 1865, __extension__ __PRETTY_FUNCTION__
))
;
1866 APValue::LValueBase Base(PVD, Index, Args.Version);
1867 LV.set(Base);
1868 // We always destroy parameters at the end of the call, even if we'd allow
1869 // them to live to the end of the full-expression at runtime, in order to
1870 // give portable results and match other compilers.
1871 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1872}
1873
1874APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1875 QualType T, ScopeKind Scope) {
1876 assert(Base.getCallIndex() == Index && "lvalue for wrong frame")(static_cast <bool> (Base.getCallIndex() == Index &&
"lvalue for wrong frame") ? void (0) : __assert_fail ("Base.getCallIndex() == Index && \"lvalue for wrong frame\""
, "clang/lib/AST/ExprConstant.cpp", 1876, __extension__ __PRETTY_FUNCTION__
))
;
1877 unsigned Version = Base.getVersion();
1878 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1879 assert(Result.isAbsent() && "local created multiple times")(static_cast <bool> (Result.isAbsent() && "local created multiple times"
) ? void (0) : __assert_fail ("Result.isAbsent() && \"local created multiple times\""
, "clang/lib/AST/ExprConstant.cpp", 1879, __extension__ __PRETTY_FUNCTION__
))
;
1880
1881 // If we're creating a local immediately in the operand of a speculative
1882 // evaluation, don't register a cleanup to be run outside the speculative
1883 // evaluation context, since we won't actually be able to initialize this
1884 // object.
1885 if (Index <= Info.SpeculativeEvaluationDepth) {
1886 if (T.isDestructedType())
1887 Info.noteSideEffect();
1888 } else {
1889 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1890 }
1891 return Result;
1892}
1893
1894APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1895 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1896 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1897 return nullptr;
1898 }
1899
1900 DynamicAllocLValue DA(NumHeapAllocs++);
1901 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1902 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1903 std::forward_as_tuple(DA), std::tuple<>());
1904 assert(Result.second && "reused a heap alloc index?")(static_cast <bool> (Result.second && "reused a heap alloc index?"
) ? void (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\""
, "clang/lib/AST/ExprConstant.cpp", 1904, __extension__ __PRETTY_FUNCTION__
))
;
1905 Result.first->second.AllocExpr = E;
1906 return &Result.first->second.Value;
1907}
1908
1909/// Produce a string describing the given constexpr call.
1910void CallStackFrame::describe(raw_ostream &Out) {
1911 unsigned ArgIndex = 0;
1912 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1913 !isa<CXXConstructorDecl>(Callee) &&
1914 cast<CXXMethodDecl>(Callee)->isInstance();
1915
1916 if (!IsMemberCall)
1917 Out << *Callee << '(';
1918
1919 if (This && IsMemberCall) {
1920 APValue Val;
1921 This->moveInto(Val);
1922 Val.printPretty(Out, Info.Ctx,
1923 This->Designator.MostDerivedType);
1924 // FIXME: Add parens around Val if needed.
1925 Out << "->" << *Callee << '(';
1926 IsMemberCall = false;
1927 }
1928
1929 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1930 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1931 if (ArgIndex > (unsigned)IsMemberCall)
1932 Out << ", ";
1933
1934 const ParmVarDecl *Param = *I;
1935 APValue *V = Info.getParamSlot(Arguments, Param);
1936 if (V)
1937 V->printPretty(Out, Info.Ctx, Param->getType());
1938 else
1939 Out << "<...>";
1940
1941 if (ArgIndex == 0 && IsMemberCall)
1942 Out << "->" << *Callee << '(';
1943 }
1944
1945 Out << ')';
1946}
1947
1948/// Evaluate an expression to see if it had side-effects, and discard its
1949/// result.
1950/// \return \c true if the caller should keep evaluating.
1951static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1952 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 1952, __extension__ __PRETTY_FUNCTION__))
;
1953 APValue Scratch;
1954 if (!Evaluate(Scratch, Info, E))
1955 // We don't need the value, but we might have skipped a side effect here.
1956 return Info.noteSideEffect();
1957 return true;
1958}
1959
1960/// Should this call expression be treated as a no-op?
1961static bool IsNoOpCall(const CallExpr *E) {
1962 unsigned Builtin = E->getBuiltinCallee();
1963 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1964 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1965 Builtin == Builtin::BI__builtin_function_start);
1966}
1967
1968static bool IsGlobalLValue(APValue::LValueBase B) {
1969 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970 // constant expression of pointer type that evaluates to...
1971
1972 // ... a null pointer value, or a prvalue core constant expression of type
1973 // std::nullptr_t.
1974 if (!B) return true;
1975
1976 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977 // ... the address of an object with static storage duration,
1978 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979 return VD->hasGlobalStorage();
1980 if (isa<TemplateParamObjectDecl>(D))
1981 return true;
1982 // ... the address of a function,
1983 // ... the address of a GUID [MS extension],
1984 // ... the address of an unnamed global constant
1985 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1986 }
1987
1988 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1989 return true;
1990
1991 const Expr *E = B.get<const Expr*>();
1992 switch (E->getStmtClass()) {
1993 default:
1994 return false;
1995 case Expr::CompoundLiteralExprClass: {
1996 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1997 return CLE->isFileScope() && CLE->isLValue();
1998 }
1999 case Expr::MaterializeTemporaryExprClass:
2000 // A materialized temporary might have been lifetime-extended to static
2001 // storage duration.
2002 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2003 // A string literal has static storage duration.
2004 case Expr::StringLiteralClass:
2005 case Expr::PredefinedExprClass:
2006 case Expr::ObjCStringLiteralClass:
2007 case Expr::ObjCEncodeExprClass:
2008 return true;
2009 case Expr::ObjCBoxedExprClass:
2010 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2011 case Expr::CallExprClass:
2012 return IsNoOpCall(cast<CallExpr>(E));
2013 // For GCC compatibility, &&label has static storage duration.
2014 case Expr::AddrLabelExprClass:
2015 return true;
2016 // A Block literal expression may be used as the initialization value for
2017 // Block variables at global or local static scope.
2018 case Expr::BlockExprClass:
2019 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2020 // The APValue generated from a __builtin_source_location will be emitted as a
2021 // literal.
2022 case Expr::SourceLocExprClass:
2023 return true;
2024 case Expr::ImplicitValueInitExprClass:
2025 // FIXME:
2026 // We can never form an lvalue with an implicit value initialization as its
2027 // base through expression evaluation, so these only appear in one case: the
2028 // implicit variable declaration we invent when checking whether a constexpr
2029 // constructor can produce a constant expression. We must assume that such
2030 // an expression might be a global lvalue.
2031 return true;
2032 }
2033}
2034
2035static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2036 return LVal.Base.dyn_cast<const ValueDecl*>();
2037}
2038
2039static bool IsLiteralLValue(const LValue &Value) {
2040 if (Value.getLValueCallIndex())
2041 return false;
2042 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2043 return E && !isa<MaterializeTemporaryExpr>(E);
2044}
2045
2046static bool IsWeakLValue(const LValue &Value) {
2047 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048 return Decl && Decl->isWeak();
2049}
2050
2051static bool isZeroSized(const LValue &Value) {
2052 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2053 if (Decl && isa<VarDecl>(Decl)) {
2054 QualType Ty = Decl->getType();
2055 if (Ty->isArrayType())
2056 return Ty->isIncompleteType() ||
2057 Decl->getASTContext().getTypeSize(Ty) == 0;
2058 }
2059 return false;
2060}
2061
2062static bool HasSameBase(const LValue &A, const LValue &B) {
2063 if (!A.getLValueBase())
2064 return !B.getLValueBase();
2065 if (!B.getLValueBase())
2066 return false;
2067
2068 if (A.getLValueBase().getOpaqueValue() !=
2069 B.getLValueBase().getOpaqueValue())
2070 return false;
2071
2072 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2073 A.getLValueVersion() == B.getLValueVersion();
2074}
2075
2076static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2077 assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue"
) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2077, __extension__ __PRETTY_FUNCTION__
))
;
2078 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2079
2080 // For a parameter, find the corresponding call stack frame (if it still
2081 // exists), and point at the parameter of the function definition we actually
2082 // invoked.
2083 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2084 unsigned Idx = PVD->getFunctionScopeIndex();
2085 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2086 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2087 F->Arguments.Version == Base.getVersion() && F->Callee &&
2088 Idx < F->Callee->getNumParams()) {
2089 VD = F->Callee->getParamDecl(Idx);
2090 break;
2091 }
2092 }
2093 }
2094
2095 if (VD)
2096 Info.Note(VD->getLocation(), diag::note_declared_at);
2097 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2098 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2099 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2100 // FIXME: Produce a note for dangling pointers too.
2101 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2102 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2103 diag::note_constexpr_dynamic_alloc_here);
2104 }
2105 // We have no information to show for a typeid(T) object.
2106}
2107
2108enum class CheckEvaluationResultKind {
2109 ConstantExpression,
2110 FullyInitialized,
2111};
2112
2113/// Materialized temporaries that we've already checked to determine if they're
2114/// initializsed by a constant expression.
2115using CheckedTemporaries =
2116 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2117
2118static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2119 EvalInfo &Info, SourceLocation DiagLoc,
2120 QualType Type, const APValue &Value,
2121 ConstantExprKind Kind,
2122 SourceLocation SubobjectLoc,
2123 CheckedTemporaries &CheckedTemps);
2124
2125/// Check that this reference or pointer core constant expression is a valid
2126/// value for an address or reference constant expression. Return true if we
2127/// can fold this expression, whether or not it's a constant expression.
2128static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2129 QualType Type, const LValue &LVal,
2130 ConstantExprKind Kind,
2131 CheckedTemporaries &CheckedTemps) {
2132 bool IsReferenceType = Type->isReferenceType();
2133
2134 APValue::LValueBase Base = LVal.getLValueBase();
2135 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2136
2137 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2138 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2139
2140 // Additional restrictions apply in a template argument. We only enforce the
2141 // C++20 restrictions here; additional syntactic and semantic restrictions
2142 // are applied elsewhere.
2143 if (isTemplateArgument(Kind)) {
2144 int InvalidBaseKind = -1;
2145 StringRef Ident;
2146 if (Base.is<TypeInfoLValue>())
2147 InvalidBaseKind = 0;
2148 else if (isa_and_nonnull<StringLiteral>(BaseE))
2149 InvalidBaseKind = 1;
2150 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2151 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2152 InvalidBaseKind = 2;
2153 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2154 InvalidBaseKind = 3;
2155 Ident = PE->getIdentKindName();
2156 }
2157
2158 if (InvalidBaseKind != -1) {
2159 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2160 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2161 << Ident;
2162 return false;
2163 }
2164 }
2165
2166 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2167 if (FD->isConsteval()) {
2168 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2169 << !Type->isAnyPointerType();
2170 Info.Note(FD->getLocation(), diag::note_declared_at);
2171 return false;
2172 }
2173 }
2174
2175 // Check that the object is a global. Note that the fake 'this' object we
2176 // manufacture when checking potential constant expressions is conservatively
2177 // assumed to be global here.
2178 if (!IsGlobalLValue(Base)) {
2179 if (Info.getLangOpts().CPlusPlus11) {
2180 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2181 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2182 << BaseVD;
2183 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2184 if (VarD && VarD->isConstexpr()) {
2185 // Non-static local constexpr variables have unintuitive semantics:
2186 // constexpr int a = 1;
2187 // constexpr const int *p = &a;
2188 // ... is invalid because the address of 'a' is not constant. Suggest
2189 // adding a 'static' in this case.
2190 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2191 << VarD
2192 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2193 } else {
2194 NoteLValueLocation(Info, Base);
2195 }
2196 } else {
2197 Info.FFDiag(Loc);
2198 }
2199 // Don't allow references to temporaries to escape.
2200 return false;
2201 }
2202 assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__
))
2203 LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__
))
2204 "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__
))
;
2205
2206 if (Base.is<DynamicAllocLValue>()) {
2207 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2208 << IsReferenceType << !Designator.Entries.empty();
2209 NoteLValueLocation(Info, Base);
2210 return false;
2211 }
2212
2213 if (BaseVD) {
2214 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2215 // Check if this is a thread-local variable.
2216 if (Var->getTLSKind())
2217 // FIXME: Diagnostic!
2218 return false;
2219
2220 // A dllimport variable never acts like a constant, unless we're
2221 // evaluating a value for use only in name mangling.
2222 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2223 // FIXME: Diagnostic!
2224 return false;
2225
2226 // In CUDA/HIP device compilation, only device side variables have
2227 // constant addresses.
2228 if (Info.getCtx().getLangOpts().CUDA &&
2229 Info.getCtx().getLangOpts().CUDAIsDevice &&
2230 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2231 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2232 !Var->hasAttr<CUDAConstantAttr>() &&
2233 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2234 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2235 Var->hasAttr<HIPManagedAttr>())
2236 return false;
2237 }
2238 }
2239 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2240 // __declspec(dllimport) must be handled very carefully:
2241 // We must never initialize an expression with the thunk in C++.
2242 // Doing otherwise would allow the same id-expression to yield
2243 // different addresses for the same function in different translation
2244 // units. However, this means that we must dynamically initialize the
2245 // expression with the contents of the import address table at runtime.
2246 //
2247 // The C language has no notion of ODR; furthermore, it has no notion of
2248 // dynamic initialization. This means that we are permitted to
2249 // perform initialization with the address of the thunk.
2250 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2251 FD->hasAttr<DLLImportAttr>())
2252 // FIXME: Diagnostic!
2253 return false;
2254 }
2255 } else if (const auto *MTE =
2256 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2257 if (CheckedTemps.insert(MTE).second) {
2258 QualType TempType = getType(Base);
2259 if (TempType.isDestructedType()) {
2260 Info.FFDiag(MTE->getExprLoc(),
2261 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2262 << TempType;
2263 return false;
2264 }
2265
2266 APValue *V = MTE->getOrCreateValue(false);
2267 assert(V && "evasluation result refers to uninitialised temporary")(static_cast <bool> (V && "evasluation result refers to uninitialised temporary"
) ? void (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\""
, "clang/lib/AST/ExprConstant.cpp", 2267, __extension__ __PRETTY_FUNCTION__
))
;
2268 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2269 Info, MTE->getExprLoc(), TempType, *V,
2270 Kind, SourceLocation(), CheckedTemps))
2271 return false;
2272 }
2273 }
2274
2275 // Allow address constant expressions to be past-the-end pointers. This is
2276 // an extension: the standard requires them to point to an object.
2277 if (!IsReferenceType)
2278 return true;
2279
2280 // A reference constant expression must refer to an object.
2281 if (!Base) {
2282 // FIXME: diagnostic
2283 Info.CCEDiag(Loc);
2284 return true;
2285 }
2286
2287 // Does this refer one past the end of some object?
2288 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2289 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2290 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2291 NoteLValueLocation(Info, Base);
2292 }
2293
2294 return true;
2295}
2296
2297/// Member pointers are constant expressions unless they point to a
2298/// non-virtual dllimport member function.
2299static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2300 SourceLocation Loc,
2301 QualType Type,
2302 const APValue &Value,
2303 ConstantExprKind Kind) {
2304 const ValueDecl *Member = Value.getMemberPointerDecl();
2305 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2306 if (!FD)
2307 return true;
2308 if (FD->isConsteval()) {
2309 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2310 Info.Note(FD->getLocation(), diag::note_declared_at);
2311 return false;
2312 }
2313 return isForManglingOnly(Kind) || FD->isVirtual() ||
2314 !FD->hasAttr<DLLImportAttr>();
2315}
2316
2317/// Check that this core constant expression is of literal type, and if not,
2318/// produce an appropriate diagnostic.
2319static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2320 const LValue *This = nullptr) {
2321 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2322 return true;
2323
2324 // C++1y: A constant initializer for an object o [...] may also invoke
2325 // constexpr constructors for o and its subobjects even if those objects
2326 // are of non-literal class types.
2327 //
2328 // C++11 missed this detail for aggregates, so classes like this:
2329 // struct foo_t { union { int i; volatile int j; } u; };
2330 // are not (obviously) initializable like so:
2331 // __attribute__((__require_constant_initialization__))
2332 // static const foo_t x = {{0}};
2333 // because "i" is a subobject with non-literal initialization (due to the
2334 // volatile member of the union). See:
2335 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2336 // Therefore, we use the C++1y behavior.
2337 if (This && Info.EvaluatingDecl == This->getLValueBase())
2338 return true;
2339
2340 // Prvalue constant expressions must be of literal types.
2341 if (Info.getLangOpts().CPlusPlus11)
2342 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2343 << E->getType();
2344 else
2345 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2346 return false;
2347}
2348
2349static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2350 EvalInfo &Info, SourceLocation DiagLoc,
2351 QualType Type, const APValue &Value,
2352 ConstantExprKind Kind,
2353 SourceLocation SubobjectLoc,
2354 CheckedTemporaries &CheckedTemps) {
2355 if (!Value.hasValue()) {
2356 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2357 << true << Type;
2358 if (SubobjectLoc.isValid())
2359 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2360 return false;
2361 }
2362
2363 // We allow _Atomic(T) to be initialized from anything that T can be
2364 // initialized from.
2365 if (const AtomicType *AT = Type->getAs<AtomicType>())
2366 Type = AT->getValueType();
2367
2368 // Core issue 1454: For a literal constant expression of array or class type,
2369 // each subobject of its value shall have been initialized by a constant
2370 // expression.
2371 if (Value.isArray()) {
2372 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2373 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2374 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2375 Value.getArrayInitializedElt(I), Kind,
2376 SubobjectLoc, CheckedTemps))
2377 return false;
2378 }
2379 if (!Value.hasArrayFiller())
2380 return true;
2381 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2382 Value.getArrayFiller(), Kind, SubobjectLoc,
2383 CheckedTemps);
2384 }
2385 if (Value.isUnion() && Value.getUnionField()) {
2386 return CheckEvaluationResult(
2387 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2388 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2389 CheckedTemps);
2390 }
2391 if (Value.isStruct()) {
2392 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2393 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2394 unsigned BaseIndex = 0;
2395 for (const CXXBaseSpecifier &BS : CD->bases()) {
2396 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2397 Value.getStructBase(BaseIndex), Kind,
2398 BS.getBeginLoc(), CheckedTemps))
2399 return false;
2400 ++BaseIndex;
2401 }
2402 }
2403 for (const auto *I : RD->fields()) {
2404 if (I->isUnnamedBitfield())
2405 continue;
2406
2407 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2408 Value.getStructField(I->getFieldIndex()),
2409 Kind, I->getLocation(), CheckedTemps))
2410 return false;
2411 }
2412 }
2413
2414 if (Value.isLValue() &&
2415 CERK == CheckEvaluationResultKind::ConstantExpression) {
2416 LValue LVal;
2417 LVal.setFrom(Info.Ctx, Value);
2418 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2419 CheckedTemps);
2420 }
2421
2422 if (Value.isMemberPointer() &&
2423 CERK == CheckEvaluationResultKind::ConstantExpression)
2424 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2425
2426 // Everything else is fine.
2427 return true;
2428}
2429
2430/// Check that this core constant expression value is a valid value for a
2431/// constant expression. If not, report an appropriate diagnostic. Does not
2432/// check that the expression is of literal type.
2433static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2434 QualType Type, const APValue &Value,
2435 ConstantExprKind Kind) {
2436 // Nothing to check for a constant expression of type 'cv void'.
2437 if (Type->isVoidType())
2438 return true;
2439
2440 CheckedTemporaries CheckedTemps;
2441 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2442 Info, DiagLoc, Type, Value, Kind,
2443 SourceLocation(), CheckedTemps);
2444}
2445
2446/// Check that this evaluated value is fully-initialized and can be loaded by
2447/// an lvalue-to-rvalue conversion.
2448static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2449 QualType Type, const APValue &Value) {
2450 CheckedTemporaries CheckedTemps;
2451 return CheckEvaluationResult(
2452 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2453 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2454}
2455
2456/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2457/// "the allocated storage is deallocated within the evaluation".
2458static bool CheckMemoryLeaks(EvalInfo &Info) {
2459 if (!Info.HeapAllocs.empty()) {
2460 // We can still fold to a constant despite a compile-time memory leak,
2461 // so long as the heap allocation isn't referenced in the result (we check
2462 // that in CheckConstantExpression).
2463 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2464 diag::note_constexpr_memory_leak)
2465 << unsigned(Info.HeapAllocs.size() - 1);
2466 }
2467 return true;
2468}
2469
2470static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2471 // A null base expression indicates a null pointer. These are always
2472 // evaluatable, and they are false unless the offset is zero.
2473 if (!Value.getLValueBase()) {
2474 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2475 Result = !Value.getLValueOffset().isZero();
2476 return true;
2477 }
2478
2479 // We have a non-null base. These are generally known to be true, but if it's
2480 // a weak declaration it can be null at runtime.
2481 Result = true;
2482 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2483 return !Decl || !Decl->isWeak();
2484}
2485
2486static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2487 // TODO: This function should produce notes if it fails.
2488 switch (Val.getKind()) {
2489 case APValue::None:
2490 case APValue::Indeterminate:
2491 return false;
2492 case APValue::Int:
2493 Result = Val.getInt().getBoolValue();
2494 return true;
2495 case APValue::FixedPoint:
2496 Result = Val.getFixedPoint().getBoolValue();
2497 return true;
2498 case APValue::Float:
2499 Result = !Val.getFloat().isZero();
2500 return true;
2501 case APValue::ComplexInt:
2502 Result = Val.getComplexIntReal().getBoolValue() ||
2503 Val.getComplexIntImag().getBoolValue();
2504 return true;
2505 case APValue::ComplexFloat:
2506 Result = !Val.getComplexFloatReal().isZero() ||
2507 !Val.getComplexFloatImag().isZero();
2508 return true;
2509 case APValue::LValue:
2510 return EvalPointerValueAsBool(Val, Result);
2511 case APValue::MemberPointer:
2512 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2513 return false;
2514 }
2515 Result = Val.getMemberPointerDecl();
2516 return true;
2517 case APValue::Vector:
2518 case APValue::Array:
2519 case APValue::Struct:
2520 case APValue::Union:
2521 case APValue::AddrLabelDiff:
2522 return false;
2523 }
2524
2525 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "clang/lib/AST/ExprConstant.cpp"
, 2525)
;
2526}
2527
2528static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2529 EvalInfo &Info) {
2530 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 2530, __extension__ __PRETTY_FUNCTION__))
;
2531 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"
) ? void (0) : __assert_fail ("E->isPRValue() && \"missing lvalue-to-rvalue conv in bool condition\""
, "clang/lib/AST/ExprConstant.cpp", 2531, __extension__ __PRETTY_FUNCTION__
))
;
2532 APValue Val;
2533 if (!Evaluate(Val, Info, E))
2534 return false;
2535 return HandleConversionToBool(Val, Result);
2536}
2537
2538template<typename T>
2539static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2540 const T &SrcValue, QualType DestType) {
2541 Info.CCEDiag(E, diag::note_constexpr_overflow)
2542 << SrcValue << DestType;
2543 return Info.noteUndefinedBehavior();
2544}
2545
2546static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2547 QualType SrcType, const APFloat &Value,
2548 QualType DestType, APSInt &Result) {
2549 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2550 // Determine whether we are converting to unsigned or signed.
2551 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2552
2553 Result = APSInt(DestWidth, !DestSigned);
2554 bool ignored;
2555 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2556 & APFloat::opInvalidOp)
2557 return HandleOverflow(Info, E, Value, DestType);
2558 return true;
2559}
2560
2561/// Get rounding mode to use in evaluation of the specified expression.
2562///
2563/// If rounding mode is unknown at compile time, still try to evaluate the
2564/// expression. If the result is exact, it does not depend on rounding mode.
2565/// So return "tonearest" mode instead of "dynamic".
2566static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2567 llvm::RoundingMode RM =
2568 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2569 if (RM == llvm::RoundingMode::Dynamic)
2570 RM = llvm::RoundingMode::NearestTiesToEven;
2571 return RM;
2572}
2573
2574/// Check if the given evaluation result is allowed for constant evaluation.
2575static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2576 APFloat::opStatus St) {
2577 // In a constant context, assume that any dynamic rounding mode or FP
2578 // exception state matches the default floating-point environment.
2579 if (Info.InConstantContext)
2580 return true;
2581
2582 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2583 if ((St & APFloat::opInexact) &&
2584 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2585 // Inexact result means that it depends on rounding mode. If the requested
2586 // mode is dynamic, the evaluation cannot be made in compile time.
2587 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2588 return false;
2589 }
2590
2591 if ((St != APFloat::opOK) &&
2592 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2593 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2594 FPO.getAllowFEnvAccess())) {
2595 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2596 return false;
2597 }
2598
2599 if ((St & APFloat::opStatus::opInvalidOp) &&
2600 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2601 // There is no usefully definable result.
2602 Info.FFDiag(E);
2603 return false;
2604 }
2605
2606 // FIXME: if:
2607 // - evaluation triggered other FP exception, and
2608 // - exception mode is not "ignore", and
2609 // - the expression being evaluated is not a part of global variable
2610 // initializer,
2611 // the evaluation probably need to be rejected.
2612 return true;
2613}
2614
2615static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2616 QualType SrcType, QualType DestType,
2617 APFloat &Result) {
2618 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E))(static_cast <bool> (isa<CastExpr>(E) || isa<CompoundAssignOperator
>(E)) ? void (0) : __assert_fail ("isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)"
, "clang/lib/AST/ExprConstant.cpp", 2618, __extension__ __PRETTY_FUNCTION__
))
;
2619 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2620 APFloat::opStatus St;
2621 APFloat Value = Result;
2622 bool ignored;
2623 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2624 return checkFloatingPointResult(Info, E, St);
2625}
2626
2627static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2628 QualType DestType, QualType SrcType,
2629 const APSInt &Value) {
2630 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2631 // Figure out if this is a truncate, extend or noop cast.
2632 // If the input is signed, do a sign extend, noop, or truncate.
2633 APSInt Result = Value.extOrTrunc(DestWidth);
2634 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2635 if (DestType->isBooleanType())
2636 Result = Value.getBoolValue();
2637 return Result;
2638}
2639
2640static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2641 const FPOptions FPO,
2642 QualType SrcType, const APSInt &Value,
2643 QualType DestType, APFloat &Result) {
2644 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2645 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2646 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2647 return checkFloatingPointResult(Info, E, St);
2648}
2649
2650static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2651 APValue &Value, const FieldDecl *FD) {
2652 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield"
) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\""
, "clang/lib/AST/ExprConstant.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
;
2653
2654 if (!Value.isInt()) {
2655 // Trying to store a pointer-cast-to-integer into a bitfield.
2656 // FIXME: In this case, we should provide the diagnostic for casting
2657 // a pointer to an integer.
2658 assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?"
) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\""
, "clang/lib/AST/ExprConstant.cpp", 2658, __extension__ __PRETTY_FUNCTION__
))
;
2659 Info.FFDiag(E);
2660 return false;
2661 }
2662
2663 APSInt &Int = Value.getInt();
2664 unsigned OldBitWidth = Int.getBitWidth();
2665 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2666 if (NewBitWidth < OldBitWidth)
2667 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2668 return true;
2669}
2670
2671static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2672 llvm::APInt &Res) {
2673 APValue SVal;
2674 if (!Evaluate(SVal, Info, E))
2675 return false;
2676 if (SVal.isInt()) {
2677 Res = SVal.getInt();
2678 return true;
2679 }
2680 if (SVal.isFloat()) {
2681 Res = SVal.getFloat().bitcastToAPInt();
2682 return true;
2683 }
2684 if (SVal.isVector()) {
2685 QualType VecTy = E->getType();
2686 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2687 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2688 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2689 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2690 Res = llvm::APInt::getZero(VecSize);
2691 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2692 APValue &Elt = SVal.getVectorElt(i);
2693 llvm::APInt EltAsInt;
2694 if (Elt.isInt()) {
2695 EltAsInt = Elt.getInt();
2696 } else if (Elt.isFloat()) {
2697 EltAsInt = Elt.getFloat().bitcastToAPInt();
2698 } else {
2699 // Don't try to handle vectors of anything other than int or float
2700 // (not sure if it's possible to hit this case).
2701 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2702 return false;
2703 }
2704 unsigned BaseEltSize = EltAsInt.getBitWidth();
2705 if (BigEndian)
2706 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2707 else
2708 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2709 }
2710 return true;
2711 }
2712 // Give up if the input isn't an int, float, or vector. For example, we
2713 // reject "(v4i16)(intptr_t)&a".
2714 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2715 return false;
2716}
2717
2718/// Perform the given integer operation, which is known to need at most BitWidth
2719/// bits, and check for overflow in the original type (if that type was not an
2720/// unsigned type).
2721template<typename Operation>
2722static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2723 const APSInt &LHS, const APSInt &RHS,
2724 unsigned BitWidth, Operation Op,
2725 APSInt &Result) {
2726 if (LHS.isUnsigned()) {
2727 Result = Op(LHS, RHS);
2728 return true;
2729 }
2730
2731 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2732 Result = Value.trunc(LHS.getBitWidth());
2733 if (Result.extend(BitWidth) != Value) {
2734 if (Info.checkingForUndefinedBehavior())
2735 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2736 diag::warn_integer_constant_overflow)
2737 << toString(Result, 10) << E->getType();
2738 return HandleOverflow(Info, E, Value, E->getType());
2739 }
2740 return true;
2741}
2742
2743/// Perform the given binary integer operation.
2744static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2745 BinaryOperatorKind Opcode, APSInt RHS,
2746 APSInt &Result) {
2747 bool HandleOverflowResult = true;
2748 switch (Opcode) {
2749 default:
2750 Info.FFDiag(E);
2751 return false;
2752 case BO_Mul:
2753 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2754 std::multiplies<APSInt>(), Result);
2755 case BO_Add:
2756 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757 std::plus<APSInt>(), Result);
2758 case BO_Sub:
2759 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2760 std::minus<APSInt>(), Result);
2761 case BO_And: Result = LHS & RHS; return true;
2762 case BO_Xor: Result = LHS ^ RHS; return true;
2763 case BO_Or: Result = LHS | RHS; return true;
2764 case BO_Div:
2765 case BO_Rem:
2766 if (RHS == 0) {
2767 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2768 return false;
2769 }
2770 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2771 // this operation and gives the two's complement result.
2772 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2773 LHS.isMinSignedValue())
2774 HandleOverflowResult = HandleOverflow(
2775 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2776 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2777 return HandleOverflowResult;
2778 case BO_Shl: {
2779 if (Info.getLangOpts().OpenCL)
2780 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2781 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2782 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2783 RHS.isUnsigned());
2784 else if (RHS.isSigned() && RHS.isNegative()) {
2785 // During constant-folding, a negative shift is an opposite shift. Such
2786 // a shift is not a constant expression.
2787 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2788 RHS = -RHS;
2789 goto shift_right;
2790 }
2791 shift_left:
2792 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2793 // the shifted type.
2794 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2795 if (SA != RHS) {
2796 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2797 << RHS << E->getType() << LHS.getBitWidth();
2798 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2799 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2800 // operand, and must not overflow the corresponding unsigned type.
2801 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2802 // E1 x 2^E2 module 2^N.
2803 if (LHS.isNegative())
2804 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2805 else if (LHS.countl_zero() < SA)
2806 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2807 }
2808 Result = LHS << SA;
2809 return true;
2810 }
2811 case BO_Shr: {
2812 if (Info.getLangOpts().OpenCL)
2813 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2814 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2815 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2816 RHS.isUnsigned());
2817 else if (RHS.isSigned() && RHS.isNegative()) {
2818 // During constant-folding, a negative shift is an opposite shift. Such a
2819 // shift is not a constant expression.
2820 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2821 RHS = -RHS;
2822 goto shift_left;
2823 }
2824 shift_right:
2825 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2826 // shifted type.
2827 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2828 if (SA != RHS)
2829 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2830 << RHS << E->getType() << LHS.getBitWidth();
2831 Result = LHS >> SA;
2832 return true;
2833 }
2834
2835 case BO_LT: Result = LHS < RHS; return true;
2836 case BO_GT: Result = LHS > RHS; return true;
2837 case BO_LE: Result = LHS <= RHS; return true;
2838 case BO_GE: Result = LHS >= RHS; return true;
2839 case BO_EQ: Result = LHS == RHS; return true;
2840 case BO_NE: Result = LHS != RHS; return true;
2841 case BO_Cmp:
2842 llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere"
, "clang/lib/AST/ExprConstant.cpp", 2842)
;
2843 }
2844}
2845
2846/// Perform the given binary floating-point operation, in-place, on LHS.
2847static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2848 APFloat &LHS, BinaryOperatorKind Opcode,
2849 const APFloat &RHS) {
2850 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2851 APFloat::opStatus St;
2852 switch (Opcode) {
2853 default:
2854 Info.FFDiag(E);
2855 return false;
2856 case BO_Mul:
2857 St = LHS.multiply(RHS, RM);
2858 break;
2859 case BO_Add:
2860 St = LHS.add(RHS, RM);
2861 break;
2862 case BO_Sub:
2863 St = LHS.subtract(RHS, RM);
2864 break;
2865 case BO_Div:
2866 // [expr.mul]p4:
2867 // If the second operand of / or % is zero the behavior is undefined.
2868 if (RHS.isZero())
2869 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2870 St = LHS.divide(RHS, RM);
2871 break;
2872 }
2873
2874 // [expr.pre]p4:
2875 // If during the evaluation of an expression, the result is not
2876 // mathematically defined [...], the behavior is undefined.
2877 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2878 if (LHS.isNaN()) {
2879 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2880 return Info.noteUndefinedBehavior();
2881 }
2882
2883 return checkFloatingPointResult(Info, E, St);
2884}
2885
2886static bool handleLogicalOpForVector(const APInt &LHSValue,
2887 BinaryOperatorKind Opcode,
2888 const APInt &RHSValue, APInt &Result) {
2889 bool LHS = (LHSValue != 0);
2890 bool RHS = (RHSValue != 0);
2891
2892 if (Opcode == BO_LAnd)
2893 Result = LHS && RHS;
2894 else
2895 Result = LHS || RHS;
2896 return true;
2897}
2898static bool handleLogicalOpForVector(const APFloat &LHSValue,
2899 BinaryOperatorKind Opcode,
2900 const APFloat &RHSValue, APInt &Result) {
2901 bool LHS = !LHSValue.isZero();
2902 bool RHS = !RHSValue.isZero();
2903
2904 if (Opcode == BO_LAnd)
2905 Result = LHS && RHS;
2906 else
2907 Result = LHS || RHS;
2908 return true;
2909}
2910
2911static bool handleLogicalOpForVector(const APValue &LHSValue,
2912 BinaryOperatorKind Opcode,
2913 const APValue &RHSValue, APInt &Result) {
2914 // The result is always an int type, however operands match the first.
2915 if (LHSValue.getKind() == APValue::Int)
2916 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2917 RHSValue.getInt(), Result);
2918 assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float
&& "Should be no other options") ? void (0) : __assert_fail
("LHSValue.getKind() == APValue::Float && \"Should be no other options\""
, "clang/lib/AST/ExprConstant.cpp", 2918, __extension__ __PRETTY_FUNCTION__
))
;
2919 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2920 RHSValue.getFloat(), Result);
2921}
2922
2923template <typename APTy>
2924static bool
2925handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2926 const APTy &RHSValue, APInt &Result) {
2927 switch (Opcode) {
2928 default:
2929 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "clang/lib/AST/ExprConstant.cpp", 2929)
;
2930 case BO_EQ:
2931 Result = (LHSValue == RHSValue);
2932 break;
2933 case BO_NE:
2934 Result = (LHSValue != RHSValue);
2935 break;
2936 case BO_LT:
2937 Result = (LHSValue < RHSValue);
2938 break;
2939 case BO_GT:
2940 Result = (LHSValue > RHSValue);
2941 break;
2942 case BO_LE:
2943 Result = (LHSValue <= RHSValue);
2944 break;
2945 case BO_GE:
2946 Result = (LHSValue >= RHSValue);
2947 break;
2948 }
2949
2950 // The boolean operations on these vector types use an instruction that
2951 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2952 // to -1 to make sure that we produce the correct value.
2953 Result.negate();
2954
2955 return true;
2956}
2957
2958static bool handleCompareOpForVector(const APValue &LHSValue,
2959 BinaryOperatorKind Opcode,
2960 const APValue &RHSValue, APInt &Result) {
2961 // The result is always an int type, however operands match the first.
2962 if (LHSValue.getKind() == APValue::Int)
2963 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2964 RHSValue.getInt(), Result);
2965 assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float
&& "Should be no other options") ? void (0) : __assert_fail
("LHSValue.getKind() == APValue::Float && \"Should be no other options\""
, "clang/lib/AST/ExprConstant.cpp", 2965, __extension__ __PRETTY_FUNCTION__
))
;
2966 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2967 RHSValue.getFloat(), Result);
2968}
2969
2970// Perform binary operations for vector types, in place on the LHS.
2971static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2972 BinaryOperatorKind Opcode,
2973 APValue &LHSValue,
2974 const APValue &RHSValue) {
2975 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&(static_cast <bool> (Opcode != BO_PtrMemD && Opcode
!= BO_PtrMemI && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 2976, __extension__ __PRETTY_FUNCTION__
))
2976 "Operation not supported on vector types")(static_cast <bool> (Opcode != BO_PtrMemD && Opcode
!= BO_PtrMemI && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 2976, __extension__ __PRETTY_FUNCTION__
))
;
2977
2978 const auto *VT = E->getType()->castAs<VectorType>();
2979 unsigned NumElements = VT->getNumElements();
2980 QualType EltTy = VT->getElementType();
2981
2982 // In the cases (typically C as I've observed) where we aren't evaluating
2983 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2984 // just give up.
2985 if (!LHSValue.isVector()) {
2986 assert(LHSValue.isLValue() &&(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue"
) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\""
, "clang/lib/AST/ExprConstant.cpp", 2987, __extension__ __PRETTY_FUNCTION__
))
2987 "A vector result that isn't a vector OR uncalculated LValue")(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue"
) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\""
, "clang/lib/AST/ExprConstant.cpp", 2987, __extension__ __PRETTY_FUNCTION__
))
;
2988 Info.FFDiag(E);
2989 return false;
2990 }
2991
2992 assert(LHSValue.getVectorLength() == NumElements &&(static_cast <bool> (LHSValue.getVectorLength() == NumElements
&& RHSValue.getVectorLength() == NumElements &&
"Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\""
, "clang/lib/AST/ExprConstant.cpp", 2993, __extension__ __PRETTY_FUNCTION__
))
2993 RHSValue.getVectorLength() == NumElements && "Different vector sizes")(static_cast <bool> (LHSValue.getVectorLength() == NumElements
&& RHSValue.getVectorLength() == NumElements &&
"Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\""
, "clang/lib/AST/ExprConstant.cpp", 2993, __extension__ __PRETTY_FUNCTION__
))
;
2994
2995 SmallVector<APValue, 4> ResultElements;
2996
2997 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2998 APValue LHSElt = LHSValue.getVectorElt(EltNum);
2999 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3000
3001 if (EltTy->isIntegerType()) {
3002 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3003 EltTy->isUnsignedIntegerType()};
3004 bool Success = true;
3005
3006 if (BinaryOperator::isLogicalOp(Opcode))
3007 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008 else if (BinaryOperator::isComparisonOp(Opcode))
3009 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3010 else
3011 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3012 RHSElt.getInt(), EltResult);
3013
3014 if (!Success) {
3015 Info.FFDiag(E);
3016 return false;
3017 }
3018 ResultElements.emplace_back(EltResult);
3019
3020 } else if (EltTy->isFloatingType()) {
3021 assert(LHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__
))
3022 RHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__
))
3023 "Mismatched LHS/RHS/Result Type")(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__
))
;
3024 APFloat LHSFloat = LHSElt.getFloat();
3025
3026 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3027 RHSElt.getFloat())) {
3028 Info.FFDiag(E);
3029 return false;
3030 }
3031
3032 ResultElements.emplace_back(LHSFloat);
3033 }
3034 }
3035
3036 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3037 return true;
3038}
3039
3040/// Cast an lvalue referring to a base subobject to a derived class, by
3041/// truncating the lvalue's path to the given length.
3042static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3043 const RecordDecl *TruncatedType,
3044 unsigned TruncatedElements) {
3045 SubobjectDesignator &D = Result.Designator;
3046
3047 // Check we actually point to a derived class object.
3048 if (TruncatedElements == D.Entries.size())
3049 return true;
3050 assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "clang/lib/AST/ExprConstant.cpp", 3051, __extension__ __PRETTY_FUNCTION__
))
3051 "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "clang/lib/AST/ExprConstant.cpp", 3051, __extension__ __PRETTY_FUNCTION__
))
;
3052 if (!Result.checkSubobject(Info, E, CSK_Derived))
3053 return false;
3054
3055 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3056 const RecordDecl *RD = TruncatedType;
3057 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3058 if (RD->isInvalidDecl()) return false;
3059 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3061 if (isVirtualBaseClass(D.Entries[I]))
3062 Result.Offset -= Layout.getVBaseClassOffset(Base);
3063 else
3064 Result.Offset -= Layout.getBaseClassOffset(Base);
3065 RD = Base;
3066 }
3067 D.Entries.resize(TruncatedElements);
3068 return true;
3069}
3070
3071static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3072 const CXXRecordDecl *Derived,
3073 const CXXRecordDecl *Base,
3074 const ASTRecordLayout *RL = nullptr) {
3075 if (!RL) {
3076 if (Derived->isInvalidDecl()) return false;
3077 RL = &Info.Ctx.getASTRecordLayout(Derived);
3078 }
3079
3080 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3081 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3082 return true;
3083}
3084
3085static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3086 const CXXRecordDecl *DerivedDecl,
3087 const CXXBaseSpecifier *Base) {
3088 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3089
3090 if (!Base->isVirtual())
3091 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3092
3093 SubobjectDesignator &D = Obj.Designator;
3094 if (D.Invalid)
3095 return false;
3096
3097 // Extract most-derived object and corresponding type.
3098 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3099 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3100 return false;
3101
3102 // Find the virtual base class.
3103 if (DerivedDecl->isInvalidDecl()) return false;
3104 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3105 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3106 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3107 return true;
3108}
3109
3110static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3111 QualType Type, LValue &Result) {
3112 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3113 PathE = E->path_end();
3114 PathI != PathE; ++PathI) {
3115 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3116 *PathI))
3117 return false;
3118 Type = (*PathI)->getType();
3119 }
3120 return true;
3121}
3122
3123/// Cast an lvalue referring to a derived class to a known base subobject.
3124static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3125 const CXXRecordDecl *DerivedRD,
3126 const CXXRecordDecl *BaseRD) {
3127 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3128 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3129 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3130 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!"
, "clang/lib/AST/ExprConstant.cpp", 3130)
;
3131
3132 for (CXXBasePathElement &Elem : Paths.front())
3133 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3134 return false;
3135 return true;
3136}
3137
3138/// Update LVal to refer to the given field, which must be a member of the type
3139/// currently described by LVal.
3140static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3141 const FieldDecl *FD,
3142 const ASTRecordLayout *RL = nullptr) {
3143 if (!RL) {
3144 if (FD->getParent()->isInvalidDecl()) return false;
3145 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3146 }
3147
3148 unsigned I = FD->getFieldIndex();
3149 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3150 LVal.addDecl(Info, E, FD);
3151 return true;
3152}
3153
3154/// Update LVal to refer to the given indirect field.
3155static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3156 LValue &LVal,
3157 const IndirectFieldDecl *IFD) {
3158 for (const auto *C : IFD->chain())
3159 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3160 return false;
3161 return true;
3162}
3163
3164/// Get the size of the given type in char units.
3165static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3166 QualType Type, CharUnits &Size) {
3167 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3168 // extension.
3169 if (Type->isVoidType() || Type->isFunctionType()) {
3170 Size = CharUnits::One();
3171 return true;
3172 }
3173
3174 if (Type->isDependentType()) {
3175 Info.FFDiag(Loc);
3176 return false;
3177 }
3178
3179 if (!Type->isConstantSizeType()) {
3180 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3181 // FIXME: Better diagnostic.
3182 Info.FFDiag(Loc);
3183 return false;
3184 }
3185
3186 Size = Info.Ctx.getTypeSizeInChars(Type);
3187 return true;
3188}
3189
3190/// Update a pointer value to model pointer arithmetic.
3191/// \param Info - Information about the ongoing evaluation.
3192/// \param E - The expression being evaluated, for diagnostic purposes.
3193/// \param LVal - The pointer value to be updated.
3194/// \param EltTy - The pointee type represented by LVal.
3195/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3196static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3197 LValue &LVal, QualType EltTy,
3198 APSInt Adjustment) {
3199 CharUnits SizeOfPointee;
3200 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3201 return false;
3202
3203 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3204 return true;
3205}
3206
3207static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3208 LValue &LVal, QualType EltTy,
3209 int64_t Adjustment) {
3210 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3211 APSInt::get(Adjustment));
3212}
3213
3214/// Update an lvalue to refer to a component of a complex number.
3215/// \param Info - Information about the ongoing evaluation.
3216/// \param LVal - The lvalue to be updated.
3217/// \param EltTy - The complex number's component type.
3218/// \param Imag - False for the real component, true for the imaginary.
3219static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3220 LValue &LVal, QualType EltTy,
3221 bool Imag) {
3222 if (Imag) {
3223 CharUnits SizeOfComponent;
3224 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3225 return false;
3226 LVal.Offset += SizeOfComponent;
3227 }
3228 LVal.addComplex(Info, E, EltTy, Imag);
3229 return true;
3230}
3231
3232/// Try to evaluate the initializer for a variable declaration.
3233///
3234/// \param Info Information about the ongoing evaluation.
3235/// \param E An expression to be used when printing diagnostics.
3236/// \param VD The variable whose initializer should be obtained.
3237/// \param Version The version of the variable within the frame.
3238/// \param Frame The frame in which the variable was created. Must be null
3239/// if this variable is not local to the evaluation.
3240/// \param Result Filled in with a pointer to the value of the variable.
3241static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3242 const VarDecl *VD, CallStackFrame *Frame,
3243 unsigned Version, APValue *&Result) {
3244 APValue::LValueBase Base(VD, Frame
9.1
'Frame' is null
? Frame->Index : 0, Version);
10
'?' condition is false
3245
3246 // If this is a local variable, dig out its value.
3247 if (Frame
10.1
'Frame' is null
) {
11
Taking false branch
3248 Result = Frame->getTemporary(VD, Version);
3249 if (Result)
3250 return true;
3251
3252 if (!isa<ParmVarDecl>(VD)) {
3253 // Assume variables referenced within a lambda's call operator that were
3254 // not declared within the call operator are captures and during checking
3255 // of a potential constant expression, assume they are unknown constant
3256 // expressions.
3257 assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__
))
3258 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__
))
3259 "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__
))
;
3260 if (Info.checkingPotentialConstantExpression())
3261 return false;
3262 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3263 // still reachable at all?
3264 Info.FFDiag(E->getBeginLoc(),
3265 diag::note_unimplemented_constexpr_lambda_feature_ast)
3266 << "captures not currently allowed";
3267 return false;
3268 }
3269 }
3270
3271 // If we're currently evaluating the initializer of this declaration, use that
3272 // in-flight value.
3273 if (Info.EvaluatingDecl == Base) {
12
Assuming the condition is false
13
Taking false branch
3274 Result = Info.EvaluatingDeclValue;
3275 return true;
3276 }
3277
3278 if (isa<ParmVarDecl>(VD)) {
14
Assuming 'VD' is a 'class clang::ParmVarDecl &'
3279 // Assume parameters of a potential constant expression are usable in
3280 // constant expressions.
3281 if (!Info.checkingPotentialConstantExpression() ||
15
Assuming the condition is false
3282 !Info.CurrentCall->Callee ||
16
Access to field 'Callee' results in a dereference of a null pointer (loaded from field 'CurrentCall')
3283 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3284 if (Info.getLangOpts().CPlusPlus11) {
3285 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3286 << VD;
3287 NoteLValueLocation(Info, Base);
3288 } else {
3289 Info.FFDiag(E);
3290 }
3291 }
3292 return false;
3293 }
3294
3295 // Dig out the initializer, and use the declaration which it's attached to.
3296 // FIXME: We should eventually check whether the variable has a reachable
3297 // initializing declaration.
3298 const Expr *Init = VD->getAnyInitializer(VD);
3299 if (!Init) {
3300 // Don't diagnose during potential constant expression checking; an
3301 // initializer might be added later.
3302 if (!Info.checkingPotentialConstantExpression()) {
3303 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3304 << VD;
3305 NoteLValueLocation(Info, Base);
3306 }
3307 return false;
3308 }
3309
3310 if (Init->isValueDependent()) {
3311 // The DeclRefExpr is not value-dependent, but the variable it refers to
3312 // has a value-dependent initializer. This should only happen in
3313 // constant-folding cases, where the variable is not actually of a suitable
3314 // type for use in a constant expression (otherwise the DeclRefExpr would
3315 // have been value-dependent too), so diagnose that.
3316 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))(static_cast <bool> (!VD->mightBeUsableInConstantExpressions
(Info.Ctx)) ? void (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)"
, "clang/lib/AST/ExprConstant.cpp", 3316, __extension__ __PRETTY_FUNCTION__
))
;
3317 if (!Info.checkingPotentialConstantExpression()) {
3318 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3319 ? diag::note_constexpr_ltor_non_constexpr
3320 : diag::note_constexpr_ltor_non_integral, 1)
3321 << VD << VD->getType();
3322 NoteLValueLocation(Info, Base);
3323 }
3324 return false;
3325 }
3326
3327 // Check that we can fold the initializer. In C++, we will have already done
3328 // this in the cases where it matters for conformance.
3329 if (!VD->evaluateValue()) {
3330 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3331 NoteLValueLocation(Info, Base);
3332 return false;
3333 }
3334
3335 // Check that the variable is actually usable in constant expressions. For a
3336 // const integral variable or a reference, we might have a non-constant
3337 // initializer that we can nonetheless evaluate the initializer for. Such
3338 // variables are not usable in constant expressions. In C++98, the
3339 // initializer also syntactically needs to be an ICE.
3340 //
3341 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3342 // expressions here; doing so would regress diagnostics for things like
3343 // reading from a volatile constexpr variable.
3344 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3345 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3346 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3347 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3348 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3349 NoteLValueLocation(Info, Base);
3350 }
3351
3352 // Never use the initializer of a weak variable, not even for constant
3353 // folding. We can't be sure that this is the definition that will be used.
3354 if (VD->isWeak()) {
3355 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3356 NoteLValueLocation(Info, Base);
3357 return false;
3358 }
3359
3360 Result = VD->getEvaluatedValue();
3361 return true;
3362}
3363
3364/// Get the base index of the given base class within an APValue representing
3365/// the given derived class.
3366static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3367 const CXXRecordDecl *Base) {
3368 Base = Base->getCanonicalDecl();
3369 unsigned Index = 0;
3370 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3371 E = Derived->bases_end(); I != E; ++I, ++Index) {
3372 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3373 return Index;
3374 }
3375
3376 llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list"
, "clang/lib/AST/ExprConstant.cpp", 3376)
;
3377}
3378
3379/// Extract the value of a character from a string literal.
3380static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3381 uint64_t Index) {
3382 assert(!isa<SourceLocExpr>(Lit) &&(static_cast <bool> (!isa<SourceLocExpr>(Lit) &&
"SourceLocExpr should have already been converted to a StringLiteral"
) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "clang/lib/AST/ExprConstant.cpp", 3383, __extension__ __PRETTY_FUNCTION__
))
3383 "SourceLocExpr should have already been converted to a StringLiteral")(static_cast <bool> (!isa<SourceLocExpr>(Lit) &&
"SourceLocExpr should have already been converted to a StringLiteral"
) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "clang/lib/AST/ExprConstant.cpp", 3383, __extension__ __PRETTY_FUNCTION__
))
;
3384
3385 // FIXME: Support MakeStringConstant
3386 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3387 std::string Str;
3388 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3389 assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large"
) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\""
, "clang/lib/AST/ExprConstant.cpp", 3389, __extension__ __PRETTY_FUNCTION__
))
;
3390 return APSInt::getUnsigned(Str.c_str()[Index]);
3391 }
3392
3393 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3394 Lit = PE->getFunctionName();
3395 const StringLiteral *S = cast<StringLiteral>(Lit);
3396 const ConstantArrayType *CAT =
3397 Info.Ctx.getAsConstantArrayType(S->getType());
3398 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "clang/lib/AST/ExprConstant.cpp", 3398, __extension__ __PRETTY_FUNCTION__
))
;
3399 QualType CharType = CAT->getElementType();
3400 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "clang/lib/AST/ExprConstant.cpp", 3400, __extension__ __PRETTY_FUNCTION__
))
;
3401
3402 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3403 CharType->isUnsignedIntegerType());
3404 if (Index < S->getLength())
3405 Value = S->getCodeUnit(Index);
3406 return Value;
3407}
3408
3409// Expand a string literal into an array of characters.
3410//
3411// FIXME: This is inefficient; we should probably introduce something similar
3412// to the LLVM ConstantDataArray to make this cheaper.
3413static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3414 APValue &Result,
3415 QualType AllocType = QualType()) {
3416 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3417 AllocType.isNull() ? S->getType() : AllocType);
3418 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "clang/lib/AST/ExprConstant.cpp", 3418, __extension__ __PRETTY_FUNCTION__
))
;
3419 QualType CharType = CAT->getElementType();
3420 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "clang/lib/AST/ExprConstant.cpp", 3420, __extension__ __PRETTY_FUNCTION__
))
;
3421
3422 unsigned Elts = CAT->getSize().getZExtValue();
3423 Result = APValue(APValue::UninitArray(),
3424 std::min(S->getLength(), Elts), Elts);
3425 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3426 CharType->isUnsignedIntegerType());
3427 if (Result.hasArrayFiller())
3428 Result.getArrayFiller() = APValue(Value);
3429 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3430 Value = S->getCodeUnit(I);
3431 Result.getArrayInitializedElt(I) = APValue(Value);
3432 }
3433}
3434
3435// Expand an array so that it has more than Index filled elements.
3436static void expandArray(APValue &Array, unsigned Index) {
3437 unsigned Size = Array.getArraySize();
3438 assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail
("Index < Size", "clang/lib/AST/ExprConstant.cpp", 3438, __extension__
__PRETTY_FUNCTION__))
;
3439
3440 // Always at least double the number of elements for which we store a value.
3441 unsigned OldElts = Array.getArrayInitializedElts();
3442 unsigned NewElts = std::max(Index+1, OldElts * 2);
3443 NewElts = std::min(Size, std::max(NewElts, 8u));
3444
3445 // Copy the data across.
3446 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3447 for (unsigned I = 0; I != OldElts; ++I)
3448 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3449 for (unsigned I = OldElts; I != NewElts; ++I)
3450 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3451 if (NewValue.hasArrayFiller())
3452 NewValue.getArrayFiller() = Array.getArrayFiller();
3453 Array.swap(NewValue);
3454}
3455
3456/// Determine whether a type would actually be read by an lvalue-to-rvalue
3457/// conversion. If it's of class type, we may assume that the copy operation
3458/// is trivial. Note that this is never true for a union type with fields
3459/// (because the copy always "reads" the active member) and always true for
3460/// a non-class type.
3461static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3462static bool isReadByLvalueToRvalueConversion(QualType T) {
3463 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3464 return !RD || isReadByLvalueToRvalueConversion(RD);
3465}
3466static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3467 // FIXME: A trivial copy of a union copies the object representation, even if
3468 // the union is empty.
3469 if (RD->isUnion())
3470 return !RD->field_empty();
3471 if (RD->isEmpty())
3472 return false;
3473
3474 for (auto *Field : RD->fields())
3475 if (!Field->isUnnamedBitfield() &&
3476 isReadByLvalueToRvalueConversion(Field->getType()))
3477 return true;
3478
3479 for (auto &BaseSpec : RD->bases())
3480 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3481 return true;
3482
3483 return false;
3484}
3485
3486/// Diagnose an attempt to read from any unreadable field within the specified
3487/// type, which might be a class type.
3488static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3489 QualType T) {
3490 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3491 if (!RD)
3492 return false;
3493
3494 if (!RD->hasMutableFields())
3495 return false;
3496
3497 for (auto *Field : RD->fields()) {
3498 // If we're actually going to read this field in some way, then it can't
3499 // be mutable. If we're in a union, then assigning to a mutable field
3500 // (even an empty one) can change the active member, so that's not OK.
3501 // FIXME: Add core issue number for the union case.
3502 if (Field->isMutable() &&
3503 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3504 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3505 Info.Note(Field->getLocation(), diag::note_declared_at);
3506 return true;
3507 }
3508
3509 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3510 return true;
3511 }
3512
3513 for (auto &BaseSpec : RD->bases())
3514 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3515 return true;
3516
3517 // All mutable fields were empty, and thus not actually read.
3518 return false;
3519}
3520
3521static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3522 APValue::LValueBase Base,
3523 bool MutableSubobject = false) {
3524 // A temporary or transient heap allocation we created.
3525 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3526 return true;
3527
3528 switch (Info.IsEvaluatingDecl) {
3529 case EvalInfo::EvaluatingDeclKind::None:
3530 return false;
3531
3532 case EvalInfo::EvaluatingDeclKind::Ctor:
3533 // The variable whose initializer we're evaluating.
3534 if (Info.EvaluatingDecl == Base)
3535 return true;
3536
3537 // A temporary lifetime-extended by the variable whose initializer we're
3538 // evaluating.
3539 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3540 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3541 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3542 return false;
3543
3544 case EvalInfo::EvaluatingDeclKind::Dtor:
3545 // C++2a [expr.const]p6:
3546 // [during constant destruction] the lifetime of a and its non-mutable
3547 // subobjects (but not its mutable subobjects) [are] considered to start
3548 // within e.
3549 if (MutableSubobject || Base != Info.EvaluatingDecl)
3550 return false;
3551 // FIXME: We can meaningfully extend this to cover non-const objects, but
3552 // we will need special handling: we should be able to access only
3553 // subobjects of such objects that are themselves declared const.
3554 QualType T = getType(Base);
3555 return T.isConstQualified() || T->isReferenceType();
3556 }
3557
3558 llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind"
, "clang/lib/AST/ExprConstant.cpp", 3558)
;
3559}
3560
3561namespace {
3562/// A handle to a complete object (an object that is not a subobject of
3563/// another object).
3564struct CompleteObject {
3565 /// The identity of the object.
3566 APValue::LValueBase Base;
3567 /// The value of the complete object.
3568 APValue *Value;
3569 /// The type of the complete object.
3570 QualType Type;
3571
3572 CompleteObject() : Value(nullptr) {}
3573 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3574 : Base(Base), Value(Value), Type(Type) {}
3575
3576 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3577 // If this isn't a "real" access (eg, if it's just accessing the type
3578 // info), allow it. We assume the type doesn't change dynamically for
3579 // subobjects of constexpr objects (even though we'd hit UB here if it
3580 // did). FIXME: Is this right?
3581 if (!isAnyAccess(AK))
3582 return true;
3583
3584 // In C++14 onwards, it is permitted to read a mutable member whose
3585 // lifetime began within the evaluation.
3586 // FIXME: Should we also allow this in C++11?
3587 if (!Info.getLangOpts().CPlusPlus14)
3588 return false;
3589 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3590 }
3591
3592 explicit operator bool() const { return !Type.isNull(); }
3593};
3594} // end anonymous namespace
3595
3596static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3597 bool IsMutable = false) {
3598 // C++ [basic.type.qualifier]p1:
3599 // - A const object is an object of type const T or a non-mutable subobject
3600 // of a const object.
3601 if (ObjType.isConstQualified() && !IsMutable)
3602 SubobjType.addConst();
3603 // - A volatile object is an object of type const T or a subobject of a
3604 // volatile object.
3605 if (ObjType.isVolatileQualified())
3606 SubobjType.addVolatile();
3607 return SubobjType;
3608}
3609
3610/// Find the designated sub-object of an rvalue.
3611template<typename SubobjectHandler>
3612typename SubobjectHandler::result_type
3613findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3614 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3615 if (Sub.Invalid)
3616 // A diagnostic will have already been produced.
3617 return handler.failed();
3618 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3619 if (Info.getLangOpts().CPlusPlus11)
3620 Info.FFDiag(E, Sub.isOnePastTheEnd()
3621 ? diag::note_constexpr_access_past_end
3622 : diag::note_constexpr_access_unsized_array)
3623 << handler.AccessKind;
3624 else
3625 Info.FFDiag(E);
3626 return handler.failed();
3627 }
3628
3629 APValue *O = Obj.Value;
3630 QualType ObjType = Obj.Type;
3631 const FieldDecl *LastField = nullptr;
3632 const FieldDecl *VolatileField = nullptr;
3633
3634 // Walk the designator's path to find the subobject.
3635 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3636 // Reading an indeterminate value is undefined, but assigning over one is OK.
3637 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3638 (O->isIndeterminate() &&
3639 !isValidIndeterminateAccess(handler.AccessKind))) {
3640 if (!Info.checkingPotentialConstantExpression())
3641 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3642 << handler.AccessKind << O->isIndeterminate();
3643 return handler.failed();
3644 }
3645
3646 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3647 // const and volatile semantics are not applied on an object under
3648 // {con,de}struction.
3649 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3650 ObjType->isRecordType() &&
3651 Info.isEvaluatingCtorDtor(
3652 Obj.Base,
3653 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3654 ConstructionPhase::None) {
3655 ObjType = Info.Ctx.getCanonicalType(ObjType);
3656 ObjType.removeLocalConst();
3657 ObjType.removeLocalVolatile();
3658 }
3659
3660 // If this is our last pass, check that the final object type is OK.
3661 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3662 // Accesses to volatile objects are prohibited.
3663 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3664 if (Info.getLangOpts().CPlusPlus) {
3665 int DiagKind;
3666 SourceLocation Loc;
3667 const NamedDecl *Decl = nullptr;
3668 if (VolatileField) {
3669 DiagKind = 2;
3670 Loc = VolatileField->getLocation();
3671 Decl = VolatileField;
3672 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3673 DiagKind = 1;
3674 Loc = VD->getLocation();
3675 Decl = VD;
3676 } else {
3677 DiagKind = 0;
3678 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3679 Loc = E->getExprLoc();
3680 }
3681 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3682 << handler.AccessKind << DiagKind << Decl;
3683 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3684 } else {
3685 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3686 }
3687 return handler.failed();
3688 }
3689
3690 // If we are reading an object of class type, there may still be more
3691 // things we need to check: if there are any mutable subobjects, we
3692 // cannot perform this read. (This only happens when performing a trivial
3693 // copy or assignment.)
3694 if (ObjType->isRecordType() &&
3695 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3696 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3697 return handler.failed();
3698 }
3699
3700 if (I == N) {
3701 if (!handler.found(*O, ObjType))
3702 return false;
3703
3704 // If we modified a bit-field, truncate it to the right width.
3705 if (isModification(handler.AccessKind) &&
3706 LastField && LastField->isBitField() &&
3707 !truncateBitfieldValue(Info, E, *O, LastField))
3708 return false;
3709
3710 return true;
3711 }
3712
3713 LastField = nullptr;
3714 if (ObjType->isArrayType()) {
3715 // Next subobject is an array element.
3716 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3717 assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?"
) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\""
, "clang/lib/AST/ExprConstant.cpp", 3717, __extension__ __PRETTY_FUNCTION__
))
;
3718 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3719 if (CAT->getSize().ule(Index)) {
3720 // Note, it should not be possible to form a pointer with a valid
3721 // designator which points more than one past the end of the array.
3722 if (Info.getLangOpts().CPlusPlus11)
3723 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3724 << handler.AccessKind;
3725 else
3726 Info.FFDiag(E);
3727 return handler.failed();
3728 }
3729
3730 ObjType = CAT->getElementType();
3731
3732 if (O->getArrayInitializedElts() > Index)
3733 O = &O->getArrayInitializedElt(Index);
3734 else if (!isRead(handler.AccessKind)) {
3735 expandArray(*O, Index);
3736 O = &O->getArrayInitializedElt(Index);
3737 } else
3738 O = &O->getArrayFiller();
3739 } else if (ObjType->isAnyComplexType()) {
3740 // Next subobject is a complex number.
3741 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3742 if (Index > 1) {
3743 if (Info.getLangOpts().CPlusPlus11)
3744 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3745 << handler.AccessKind;
3746 else
3747 Info.FFDiag(E);
3748 return handler.failed();
3749 }
3750
3751 ObjType = getSubobjectType(
3752 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3753
3754 assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?"
) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\""
, "clang/lib/AST/ExprConstant.cpp", 3754, __extension__ __PRETTY_FUNCTION__
))
;
3755 if (O->isComplexInt()) {
3756 return handler.found(Index ? O->getComplexIntImag()
3757 : O->getComplexIntReal(), ObjType);
3758 } else {
3759 assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0)
: __assert_fail ("O->isComplexFloat()", "clang/lib/AST/ExprConstant.cpp"
, 3759, __extension__ __PRETTY_FUNCTION__))
;
3760 return handler.found(Index ? O->getComplexFloatImag()
3761 : O->getComplexFloatReal(), ObjType);
3762 }
3763 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3764 if (Field->isMutable() &&
3765 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3766 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3767 << handler.AccessKind << Field;
3768 Info.Note(Field->getLocation(), diag::note_declared_at);
3769 return handler.failed();
3770 }
3771
3772 // Next subobject is a class, struct or union field.
3773 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3774 if (RD->isUnion()) {
3775 const FieldDecl *UnionField = O->getUnionField();
3776 if (!UnionField ||
3777 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3778 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3779 // Placement new onto an inactive union member makes it active.
3780 O->setUnion(Field, APValue());
3781 } else {
3782 // FIXME: If O->getUnionValue() is absent, report that there's no
3783 // active union member rather than reporting the prior active union
3784 // member. We'll need to fix nullptr_t to not use APValue() as its
3785 // representation first.
3786 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3787 << handler.AccessKind << Field << !UnionField << UnionField;
3788 return handler.failed();
3789 }
3790 }
3791 O = &O->getUnionValue();
3792 } else
3793 O = &O->getStructField(Field->getFieldIndex());
3794
3795 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3796 LastField = Field;
3797 if (Field->getType().isVolatileQualified())
3798 VolatileField = Field;
3799 } else {
3800 // Next subobject is a base class.
3801 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3802 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3803 O = &O->getStructBase(getBaseIndex(Derived, Base));
3804
3805 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3806 }
3807 }
3808}
3809
3810namespace {
3811struct ExtractSubobjectHandler {
3812 EvalInfo &Info;
3813 const Expr *E;
3814 APValue &Result;
3815 const AccessKinds AccessKind;
3816
3817 typedef bool result_type;
3818 bool failed() { return false; }
3819 bool found(APValue &Subobj, QualType SubobjType) {
3820 Result = Subobj;
3821 if (AccessKind == AK_ReadObjectRepresentation)
3822 return true;
3823 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3824 }
3825 bool found(APSInt &Value, QualType SubobjType) {
3826 Result = APValue(Value);
3827 return true;
3828 }
3829 bool found(APFloat &Value, QualType SubobjType) {
3830 Result = APValue(Value);
3831 return true;
3832 }
3833};
3834} // end anonymous namespace
3835
3836/// Extract the designated sub-object of an rvalue.
3837static bool extractSubobject(EvalInfo &Info, const Expr *E,
3838 const CompleteObject &Obj,
3839 const SubobjectDesignator &Sub, APValue &Result,
3840 AccessKinds AK = AK_Read) {
3841 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)(static_cast <bool> (AK == AK_Read || AK == AK_ReadObjectRepresentation
) ? void (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation"
, "clang/lib/AST/ExprConstant.cpp", 3841, __extension__ __PRETTY_FUNCTION__
))
;
3842 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3843 return findSubobject(Info, E, Obj, Sub, Handler);
3844}
3845
3846namespace {
3847struct ModifySubobjectHandler {
3848 EvalInfo &Info;
3849 APValue &NewVal;
3850 const Expr *E;
3851
3852 typedef bool result_type;
3853 static const AccessKinds AccessKind = AK_Assign;
3854
3855 bool checkConst(QualType QT) {
3856 // Assigning to a const object has undefined behavior.
3857 if (QT.isConstQualified()) {
3858 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3859 return false;
3860 }
3861 return true;
3862 }
3863
3864 bool failed() { return false; }
3865 bool found(APValue &Subobj, QualType SubobjType) {
3866 if (!checkConst(SubobjType))
3867 return false;
3868 // We've been given ownership of NewVal, so just swap it in.
3869 Subobj.swap(NewVal);
3870 return true;
3871 }
3872 bool found(APSInt &Value, QualType SubobjType) {
3873 if (!checkConst(SubobjType))
3874 return false;
3875 if (!NewVal.isInt()) {
3876 // Maybe trying to write a cast pointer value into a complex?
3877 Info.FFDiag(E);
3878 return false;
3879 }
3880 Value = NewVal.getInt();
3881 return true;
3882 }
3883 bool found(APFloat &Value, QualType SubobjType) {
3884 if (!checkConst(SubobjType))
3885 return false;
3886 Value = NewVal.getFloat();
3887 return true;
3888 }
3889};
3890} // end anonymous namespace
3891
3892const AccessKinds ModifySubobjectHandler::AccessKind;
3893
3894/// Update the designated sub-object of an rvalue to the given value.
3895static bool modifySubobject(EvalInfo &Info, const Expr *E,
3896 const CompleteObject &Obj,
3897 const SubobjectDesignator &Sub,
3898 APValue &NewVal) {
3899 ModifySubobjectHandler Handler = { Info, NewVal, E };
3900 return findSubobject(Info, E, Obj, Sub, Handler);
3901}
3902
3903/// Find the position where two subobject designators diverge, or equivalently
3904/// the length of the common initial subsequence.
3905static unsigned FindDesignatorMismatch(QualType ObjType,
3906 const SubobjectDesignator &A,
3907 const SubobjectDesignator &B,
3908 bool &WasArrayIndex) {
3909 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3910 for (/**/; I != N; ++I) {
3911 if (!ObjType.isNull() &&
3912 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3913 // Next subobject is an array element.
3914 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3915 WasArrayIndex = true;
3916 return I;
3917 }
3918 if (ObjType->isAnyComplexType())
3919 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3920 else
3921 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3922 } else {
3923 if (A.Entries[I].getAsBaseOrMember() !=
3924 B.Entries[I].getAsBaseOrMember()) {
3925 WasArrayIndex = false;
3926 return I;
3927 }
3928 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3929 // Next subobject is a field.
3930 ObjType = FD->getType();
3931 else
3932 // Next subobject is a base class.
3933 ObjType = QualType();
3934 }
3935 }
3936 WasArrayIndex = false;
3937 return I;
3938}
3939
3940/// Determine whether the given subobject designators refer to elements of the
3941/// same array object.
3942static bool AreElementsOfSameArray(QualType ObjType,
3943 const SubobjectDesignator &A,
3944 const SubobjectDesignator &B) {
3945 if (A.Entries.size() != B.Entries.size())
3946 return false;
3947
3948 bool IsArray = A.MostDerivedIsArrayElement;
3949 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3950 // A is a subobject of the array element.
3951 return false;
3952
3953 // If A (and B) designates an array element, the last entry will be the array
3954 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3955 // of length 1' case, and the entire path must match.
3956 bool WasArrayIndex;
3957 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3958 return CommonLength >= A.Entries.size() - IsArray;
3959}
3960
3961/// Find the complete object to which an LValue refers.
3962static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3963 AccessKinds AK, const LValue &LVal,
3964 QualType LValType) {
3965 if (LVal.InvalidBase) {
3966 Info.FFDiag(E);
3967 return CompleteObject();
3968 }
3969
3970 if (!LVal.Base) {
3971 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3972 return CompleteObject();
3973 }
3974
3975 CallStackFrame *Frame = nullptr;
3976 unsigned Depth = 0;
3977 if (LVal.getLValueCallIndex()) {
3978 std::tie(Frame, Depth) =
3979 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3980 if (!Frame) {
3981 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3982 << AK << LVal.Base.is<const ValueDecl*>();
3983 NoteLValueLocation(Info, LVal.Base);
3984 return CompleteObject();
3985 }
3986 }
3987
3988 bool IsAccess = isAnyAccess(AK);
3989
3990 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3991 // is not a constant expression (even if the object is non-volatile). We also
3992 // apply this rule to C++98, in order to conform to the expected 'volatile'
3993 // semantics.
3994 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3995 if (Info.getLangOpts().CPlusPlus)
3996 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3997 << AK << LValType;
3998 else
3999 Info.FFDiag(E);
4000 return CompleteObject();
4001 }
4002
4003 // Compute value storage location and type of base object.
4004 APValue *BaseVal = nullptr;
4005 QualType BaseType = getType(LVal.Base);
4006
4007 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4008 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4009 // This is the object whose initializer we're evaluating, so its lifetime
4010 // started in the current evaluation.
4011 BaseVal = Info.EvaluatingDeclValue;
4012 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4013 // Allow reading from a GUID declaration.
4014 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4015 if (isModification(AK)) {
4016 // All the remaining cases do not permit modification of the object.
4017 Info.FFDiag(E, diag::note_constexpr_modify_global);
4018 return CompleteObject();
4019 }
4020 APValue &V = GD->getAsAPValue();
4021 if (V.isAbsent()) {
4022 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4023 << GD->getType();
4024 return CompleteObject();
4025 }
4026 return CompleteObject(LVal.Base, &V, GD->getType());
4027 }
4028
4029 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4030 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4031 if (isModification(AK)) {
4032 Info.FFDiag(E, diag::note_constexpr_modify_global);
4033 return CompleteObject();
4034 }
4035 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4036 GCD->getType());
4037 }
4038
4039 // Allow reading from template parameter objects.
4040 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4041 if (isModification(AK)) {
4042 Info.FFDiag(E, diag::note_constexpr_modify_global);
4043 return CompleteObject();
4044 }
4045 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4046 TPO->getType());
4047 }
4048
4049 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4050 // In C++11, constexpr, non-volatile variables initialized with constant
4051 // expressions are constant expressions too. Inside constexpr functions,
4052 // parameters are constant expressions even if they're non-const.
4053 // In C++1y, objects local to a constant expression (those with a Frame) are
4054 // both readable and writable inside constant expressions.
4055 // In C, such things can also be folded, although they are not ICEs.
4056 const VarDecl *VD = dyn_cast<VarDecl>(D);
4057 if (VD) {
4058 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4059 VD = VDef;
4060 }
4061 if (!VD || VD->isInvalidDecl()) {
4062 Info.FFDiag(E);
4063 return CompleteObject();
4064 }
4065
4066 bool IsConstant = BaseType.isConstant(Info.Ctx);
4067
4068 // Unless we're looking at a local variable or argument in a constexpr call,
4069 // the variable we're reading must be const.
4070 if (!Frame) {
4071 if (IsAccess && isa<ParmVarDecl>(VD)) {
4072 // Access of a parameter that's not associated with a frame isn't going
4073 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4074 // suitable diagnostic.
4075 } else if (Info.getLangOpts().CPlusPlus14 &&
4076 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4077 // OK, we can read and modify an object if we're in the process of
4078 // evaluating its initializer, because its lifetime began in this
4079 // evaluation.
4080 } else if (isModification(AK)) {
4081 // All the remaining cases do not permit modification of the object.
4082 Info.FFDiag(E, diag::note_constexpr_modify_global);
4083 return CompleteObject();
4084 } else if (VD->isConstexpr()) {
4085 // OK, we can read this variable.
4086 } else if (BaseType->isIntegralOrEnumerationType()) {
4087 if (!IsConstant) {
4088 if (!IsAccess)
4089 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4090 if (Info.getLangOpts().CPlusPlus) {
4091 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4092 Info.Note(VD->getLocation(), diag::note_declared_at);
4093 } else {
4094 Info.FFDiag(E);
4095 }
4096 return CompleteObject();
4097 }
4098 } else if (!IsAccess) {
4099 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4100 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4101 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4102 // This variable might end up being constexpr. Don't diagnose it yet.
4103 } else if (IsConstant) {
4104 // Keep evaluating to see what we can do. In particular, we support
4105 // folding of const floating-point types, in order to make static const
4106 // data members of such types (supported as an extension) more useful.
4107 if (Info.getLangOpts().CPlusPlus) {
4108 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4109 ? diag::note_constexpr_ltor_non_constexpr
4110 : diag::note_constexpr_ltor_non_integral, 1)
4111 << VD << BaseType;
4112 Info.Note(VD->getLocation(), diag::note_declared_at);
4113 } else {
4114 Info.CCEDiag(E);
4115 }
4116 } else {
4117 // Never allow reading a non-const value.
4118 if (Info.getLangOpts().CPlusPlus) {
4119 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4120 ? diag::note_constexpr_ltor_non_constexpr
4121 : diag::note_constexpr_ltor_non_integral, 1)
4122 << VD << BaseType;
4123 Info.Note(VD->getLocation(), diag::note_declared_at);
4124 } else {
4125 Info.FFDiag(E);
4126 }
4127 return CompleteObject();
4128 }
4129 }
4130
4131 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4132 return CompleteObject();
4133 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4134 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4135 if (!Alloc) {
4136 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4137 return CompleteObject();
4138 }
4139 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4140 LVal.Base.getDynamicAllocType());
4141 } else {
4142 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4143
4144 if (!Frame) {
4145 if (const MaterializeTemporaryExpr *MTE =
4146 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4147 assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4148, __extension__ __PRETTY_FUNCTION__
))
4148 "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4148, __extension__ __PRETTY_FUNCTION__
))
;
4149
4150 // C++20 [expr.const]p4: [DR2126]
4151 // An object or reference is usable in constant expressions if it is
4152 // - a temporary object of non-volatile const-qualified literal type
4153 // whose lifetime is extended to that of a variable that is usable
4154 // in constant expressions
4155 //
4156 // C++20 [expr.const]p5:
4157 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4158 // - a non-volatile glvalue that refers to an object that is usable
4159 // in constant expressions, or
4160 // - a non-volatile glvalue of literal type that refers to a
4161 // non-volatile object whose lifetime began within the evaluation
4162 // of E;
4163 //
4164 // C++11 misses the 'began within the evaluation of e' check and
4165 // instead allows all temporaries, including things like:
4166 // int &&r = 1;
4167 // int x = ++r;
4168 // constexpr int k = r;
4169 // Therefore we use the C++14-onwards rules in C++11 too.
4170 //
4171 // Note that temporaries whose lifetimes began while evaluating a
4172 // variable's constructor are not usable while evaluating the
4173 // corresponding destructor, not even if they're of const-qualified
4174 // types.
4175 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4176 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4177 if (!IsAccess)
4178 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4179 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4180 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4181 return CompleteObject();
4182 }
4183
4184 BaseVal = MTE->getOrCreateValue(false);
4185 assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary"
) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4185, __extension__ __PRETTY_FUNCTION__
))
;
4186 } else {
4187 if (!IsAccess)
4188 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4189 APValue Val;
4190 LVal.moveInto(Val);
4191 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4192 << AK
4193 << Val.getAsString(Info.Ctx,
4194 Info.Ctx.getLValueReferenceType(LValType));
4195 NoteLValueLocation(Info, LVal.Base);
4196 return CompleteObject();
4197 }
4198 } else {
4199 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4200 assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary"
) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4200, __extension__ __PRETTY_FUNCTION__
))
;
4201 }
4202 }
4203
4204 // In C++14, we can't safely access any mutable state when we might be
4205 // evaluating after an unmodeled side effect. Parameters are modeled as state
4206 // in the caller, but aren't visible once the call returns, so they can be
4207 // modified in a speculatively-evaluated call.
4208 //
4209 // FIXME: Not all local state is mutable. Allow local constant subobjects
4210 // to be read here (but take care with 'mutable' fields).
4211 unsigned VisibleDepth = Depth;
4212 if (llvm::isa_and_nonnull<ParmVarDecl>(
4213 LVal.Base.dyn_cast<const ValueDecl *>()))
4214 ++VisibleDepth;
4215 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4216 Info.EvalStatus.HasSideEffects) ||
4217 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4218 return CompleteObject();
4219
4220 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4221}
4222
4223/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4224/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4225/// glvalue referred to by an entity of reference type.
4226///
4227/// \param Info - Information about the ongoing evaluation.
4228/// \param Conv - The expression for which we are performing the conversion.
4229/// Used for diagnostics.
4230/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4231/// case of a non-class type).
4232/// \param LVal - The glvalue on which we are attempting to perform this action.
4233/// \param RVal - The produced value will be placed here.
4234/// \param WantObjectRepresentation - If true, we're looking for the object
4235/// representation rather than the value, and in particular,
4236/// there is no requirement that the result be fully initialized.
4237static bool
4238handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4239 const LValue &LVal, APValue &RVal,
4240 bool WantObjectRepresentation = false) {
4241 if (LVal.Designator.Invalid)
4242 return false;
4243
4244 // Check for special cases where there is no existing APValue to look at.
4245 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4246
4247 AccessKinds AK =
4248 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4249
4250 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4251 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4252 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4253 // initializer until now for such expressions. Such an expression can't be
4254 // an ICE in C, so this only matters for fold.
4255 if (Type.isVolatileQualified()) {
4256 Info.FFDiag(Conv);
4257 return false;
4258 }
4259
4260 APValue Lit;
4261 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4262 return false;
4263
4264 // According to GCC info page:
4265 //
4266 // 6.28 Compound Literals
4267 //
4268 // As an optimization, G++ sometimes gives array compound literals longer
4269 // lifetimes: when the array either appears outside a function or has a
4270 // const-qualified type. If foo and its initializer had elements of type
4271 // char *const rather than char *, or if foo were a global variable, the
4272 // array would have static storage duration. But it is probably safest
4273 // just to avoid the use of array compound literals in C++ code.
4274 //
4275 // Obey that rule by checking constness for converted array types.
4276
4277 QualType CLETy = CLE->getType();
4278 if (CLETy->isArrayType() && !Type->isArrayType()) {
4279 if (!CLETy.isConstant(Info.Ctx)) {
4280 Info.FFDiag(Conv);
4281 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4282 return false;
4283 }
4284 }
4285
4286 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4287 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4288 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4289 // Special-case character extraction so we don't have to construct an
4290 // APValue for the whole string.
4291 assert(LVal.Designator.Entries.size() <= 1 &&(static_cast <bool> (LVal.Designator.Entries.size() <=
1 && "Can only read characters from string literals"
) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "clang/lib/AST/ExprConstant.cpp", 4292, __extension__ __PRETTY_FUNCTION__
))
4292 "Can only read characters from string literals")(static_cast <bool> (LVal.Designator.Entries.size() <=
1 && "Can only read characters from string literals"
) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "clang/lib/AST/ExprConstant.cpp", 4292, __extension__ __PRETTY_FUNCTION__
))
;
4293 if (LVal.Designator.Entries.empty()) {
4294 // Fail for now for LValue to RValue conversion of an array.
4295 // (This shouldn't show up in C/C++, but it could be triggered by a
4296 // weird EvaluateAsRValue call from a tool.)
4297 Info.FFDiag(Conv);
4298 return false;
4299 }
4300 if (LVal.Designator.isOnePastTheEnd()) {
4301 if (Info.getLangOpts().CPlusPlus11)
4302 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4303 else
4304 Info.FFDiag(Conv);
4305 return false;
4306 }
4307 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4308 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4309 return true;
4310 }
4311 }
4312
4313 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4314 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4315}
4316
4317/// Perform an assignment of Val to LVal. Takes ownership of Val.
4318static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4319 QualType LValType, APValue &Val) {
4320 if (LVal.Designator.Invalid)
4321 return false;
4322
4323 if (!Info.getLangOpts().CPlusPlus14) {
4324 Info.FFDiag(E);
4325 return false;
4326 }
4327
4328 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4329 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4330}
4331
4332namespace {
4333struct CompoundAssignSubobjectHandler {
4334 EvalInfo &Info;
4335 const CompoundAssignOperator *E;
4336 QualType PromotedLHSType;
4337 BinaryOperatorKind Opcode;
4338 const APValue &RHS;
4339
4340 static const AccessKinds AccessKind = AK_Assign;
4341
4342 typedef bool result_type;
4343
4344 bool checkConst(QualType QT) {
4345 // Assigning to a const object has undefined behavior.
4346 if (QT.isConstQualified()) {
4347 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4348 return false;
4349 }
4350 return true;
4351 }
4352
4353 bool failed() { return false; }
4354 bool found(APValue &Subobj, QualType SubobjType) {
4355 switch (Subobj.getKind()) {
4356 case APValue::Int:
4357 return found(Subobj.getInt(), SubobjType);
4358 case APValue::Float:
4359 return found(Subobj.getFloat(), SubobjType);
4360 case APValue::ComplexInt:
4361 case APValue::ComplexFloat:
4362 // FIXME: Implement complex compound assignment.
4363 Info.FFDiag(E);
4364 return false;
4365 case APValue::LValue:
4366 return foundPointer(Subobj, SubobjType);
4367 case APValue::Vector:
4368 return foundVector(Subobj, SubobjType);
4369 default:
4370 // FIXME: can this happen?
4371 Info.FFDiag(E);
4372 return false;
4373 }
4374 }
4375
4376 bool foundVector(APValue &Value, QualType SubobjType) {
4377 if (!checkConst(SubobjType))
4378 return false;
4379
4380 if (!SubobjType->isVectorType()) {
4381 Info.FFDiag(E);
4382 return false;
4383 }
4384 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4385 }
4386
4387 bool found(APSInt &Value, QualType SubobjType) {
4388 if (!checkConst(SubobjType))
4389 return false;
4390
4391 if (!SubobjType->isIntegerType()) {
4392 // We don't support compound assignment on integer-cast-to-pointer
4393 // values.
4394 Info.FFDiag(E);
4395 return false;
4396 }
4397
4398 if (RHS.isInt()) {
4399 APSInt LHS =
4400 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4401 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4402 return false;
4403 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4404 return true;
4405 } else if (RHS.isFloat()) {
4406 const FPOptions FPO = E->getFPFeaturesInEffect(
4407 Info.Ctx.getLangOpts());
4408 APFloat FValue(0.0);
4409 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4410 PromotedLHSType, FValue) &&
4411 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4412 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4413 Value);
4414 }
4415
4416 Info.FFDiag(E);
4417 return false;
4418 }
4419 bool found(APFloat &Value, QualType SubobjType) {
4420 return checkConst(SubobjType) &&
4421 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4422 Value) &&
4423 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4424 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4425 }
4426 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4427 if (!checkConst(SubobjType))
4428 return false;
4429
4430 QualType PointeeType;
4431 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4432 PointeeType = PT->getPointeeType();
4433
4434 if (PointeeType.isNull() || !RHS.isInt() ||
4435 (Opcode != BO_Add && Opcode != BO_Sub)) {
4436 Info.FFDiag(E);
4437 return false;
4438 }
4439
4440 APSInt Offset = RHS.getInt();
4441 if (Opcode == BO_Sub)
4442 negateAsSigned(Offset);
4443
4444 LValue LVal;
4445 LVal.setFrom(Info.Ctx, Subobj);
4446 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4447 return false;
4448 LVal.moveInto(Subobj);
4449 return true;
4450 }
4451};
4452} // end anonymous namespace
4453
4454const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4455
4456/// Perform a compound assignment of LVal <op>= RVal.
4457static bool handleCompoundAssignment(EvalInfo &Info,
4458 const CompoundAssignOperator *E,
4459 const LValue &LVal, QualType LValType,
4460 QualType PromotedLValType,
4461 BinaryOperatorKind Opcode,
4462 const APValue &RVal) {
4463 if (LVal.Designator.Invalid)
4464 return false;
4465
4466 if (!Info.getLangOpts().CPlusPlus14) {
4467 Info.FFDiag(E);
4468 return false;
4469 }
4470
4471 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4472 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4473 RVal };
4474 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4475}
4476
4477namespace {
4478struct IncDecSubobjectHandler {
4479 EvalInfo &Info;
4480 const UnaryOperator *E;
4481 AccessKinds AccessKind;
4482 APValue *Old;
4483
4484 typedef bool result_type;
4485
4486 bool checkConst(QualType QT) {
4487 // Assigning to a const object has undefined behavior.
4488 if (QT.isConstQualified()) {
4489 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4490 return false;
4491 }
4492 return true;
4493 }
4494
4495 bool failed() { return false; }
4496 bool found(APValue &Subobj, QualType SubobjType) {
4497 // Stash the old value. Also clear Old, so we don't clobber it later
4498 // if we're post-incrementing a complex.
4499 if (Old) {
4500 *Old = Subobj;
4501 Old = nullptr;
4502 }
4503
4504 switch (Subobj.getKind()) {
4505 case APValue::Int:
4506 return found(Subobj.getInt(), SubobjType);
4507 case APValue::Float:
4508 return found(Subobj.getFloat(), SubobjType);
4509 case APValue::ComplexInt:
4510 return found(Subobj.getComplexIntReal(),
4511 SubobjType->castAs<ComplexType>()->getElementType()
4512 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4513 case APValue::ComplexFloat:
4514 return found(Subobj.getComplexFloatReal(),
4515 SubobjType->castAs<ComplexType>()->getElementType()
4516 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4517 case APValue::LValue:
4518 return foundPointer(Subobj, SubobjType);
4519 default:
4520 // FIXME: can this happen?
4521 Info.FFDiag(E);
4522 return false;
4523 }
4524 }
4525 bool found(APSInt &Value, QualType SubobjType) {
4526 if (!checkConst(SubobjType))
4527 return false;
4528
4529 if (!SubobjType->isIntegerType()) {
4530 // We don't support increment / decrement on integer-cast-to-pointer
4531 // values.
4532 Info.FFDiag(E);
4533 return false;
4534 }
4535
4536 if (Old) *Old = APValue(Value);
4537
4538 // bool arithmetic promotes to int, and the conversion back to bool
4539 // doesn't reduce mod 2^n, so special-case it.
4540 if (SubobjType->isBooleanType()) {
4541 if (AccessKind == AK_Increment)
4542 Value = 1;
4543 else
4544 Value = !Value;
4545 return true;
4546 }
4547
4548 bool WasNegative = Value.isNegative();
4549 if (AccessKind == AK_Increment) {
4550 ++Value;
4551
4552 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4553 APSInt ActualValue(Value, /*IsUnsigned*/true);
4554 return HandleOverflow(Info, E, ActualValue, SubobjType);
4555 }
4556 } else {
4557 --Value;
4558
4559 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4560 unsigned BitWidth = Value.getBitWidth();
4561 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4562 ActualValue.setBit(BitWidth);
4563 return HandleOverflow(Info, E, ActualValue, SubobjType);
4564 }
4565 }
4566 return true;
4567 }
4568 bool found(APFloat &Value, QualType SubobjType) {
4569 if (!checkConst(SubobjType))
4570 return false;
4571
4572 if (Old) *Old = APValue(Value);
4573
4574 APFloat One(Value.getSemantics(), 1);
4575 if (AccessKind == AK_Increment)
4576 Value.add(One, APFloat::rmNearestTiesToEven);
4577 else
4578 Value.subtract(One, APFloat::rmNearestTiesToEven);
4579 return true;
4580 }
4581 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4582 if (!checkConst(SubobjType))
4583 return false;
4584
4585 QualType PointeeType;
4586 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4587 PointeeType = PT->getPointeeType();
4588 else {
4589 Info.FFDiag(E);
4590 return false;
4591 }
4592
4593 LValue LVal;
4594 LVal.setFrom(Info.Ctx, Subobj);
4595 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4596 AccessKind == AK_Increment ? 1 : -1))
4597 return false;
4598 LVal.moveInto(Subobj);
4599 return true;
4600 }
4601};
4602} // end anonymous namespace
4603
4604/// Perform an increment or decrement on LVal.
4605static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4606 QualType LValType, bool IsIncrement, APValue *Old) {
4607 if (LVal.Designator.Invalid)
4608 return false;
4609
4610 if (!Info.getLangOpts().CPlusPlus14) {
4611 Info.FFDiag(E);
4612 return false;
4613 }
4614
4615 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4616 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4617 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4618 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4619}
4620
4621/// Build an lvalue for the object argument of a member function call.
4622static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4623 LValue &This) {
4624 if (Object->getType()->isPointerType() && Object->isPRValue())
4625 return EvaluatePointer(Object, This, Info);
4626
4627 if (Object->isGLValue())
4628 return EvaluateLValue(Object, This, Info);
4629
4630 if (Object->getType()->isLiteralType(Info.Ctx))
4631 return EvaluateTemporary(Object, This, Info);
4632
4633 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4634 return false;
4635}
4636
4637/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4638/// lvalue referring to the result.
4639///
4640/// \param Info - Information about the ongoing evaluation.
4641/// \param LV - An lvalue referring to the base of the member pointer.
4642/// \param RHS - The member pointer expression.
4643/// \param IncludeMember - Specifies whether the member itself is included in
4644/// the resulting LValue subobject designator. This is not possible when
4645/// creating a bound member function.
4646/// \return The field or method declaration to which the member pointer refers,
4647/// or 0 if evaluation fails.
4648static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4649 QualType LVType,
4650 LValue &LV,
4651 const Expr *RHS,
4652 bool IncludeMember = true) {
4653 MemberPtr MemPtr;
4654 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4655 return nullptr;
4656
4657 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4658 // member value, the behavior is undefined.
4659 if (!MemPtr.getDecl()) {
4660 // FIXME: Specific diagnostic.
4661 Info.FFDiag(RHS);
4662 return nullptr;
4663 }
4664
4665 if (MemPtr.isDerivedMember()) {
4666 // This is a member of some derived class. Truncate LV appropriately.
4667 // The end of the derived-to-base path for the base object must match the
4668 // derived-to-base path for the member pointer.
4669 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4670 LV.Designator.Entries.size()) {
4671 Info.FFDiag(RHS);
4672 return nullptr;
4673 }
4674 unsigned PathLengthToMember =
4675 LV.Designator.Entries.size() - MemPtr.Path.size();
4676 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4677 const CXXRecordDecl *LVDecl = getAsBaseClass(
4678 LV.Designator.Entries[PathLengthToMember + I]);
4679 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4680 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4681 Info.FFDiag(RHS);
4682 return nullptr;
4683 }
4684 }
4685
4686 // Truncate the lvalue to the appropriate derived class.
4687 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4688 PathLengthToMember))
4689 return nullptr;
4690 } else if (!MemPtr.Path.empty()) {
4691 // Extend the LValue path with the member pointer's path.
4692 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4693 MemPtr.Path.size() + IncludeMember);
4694
4695 // Walk down to the appropriate base class.
4696 if (const PointerType *PT = LVType->getAs<PointerType>())
4697 LVType = PT->getPointeeType();
4698 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4699 assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression"
) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\""
, "clang/lib/AST/ExprConstant.cpp", 4699, __extension__ __PRETTY_FUNCTION__
))
;
4700 // The first class in the path is that of the lvalue.
4701 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4702 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4703 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4704 return nullptr;
4705 RD = Base;
4706 }
4707 // Finally cast to the class containing the member.
4708 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4709 MemPtr.getContainingRecord()))
4710 return nullptr;
4711 }
4712
4713 // Add the member. Note that we cannot build bound member functions here.
4714 if (IncludeMember) {
4715 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4716 if (!HandleLValueMember(Info, RHS, LV, FD))
4717 return nullptr;
4718 } else if (const IndirectFieldDecl *IFD =
4719 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4720 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4721 return nullptr;
4722 } else {
4723 llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function"
, "clang/lib/AST/ExprConstant.cpp", 4723)
;
4724 }
4725 }
4726
4727 return MemPtr.getDecl();
4728}
4729
4730static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4731 const BinaryOperator *BO,
4732 LValue &LV,
4733 bool IncludeMember = true) {
4734 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD ||
BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI"
, "clang/lib/AST/ExprConstant.cpp", 4734, __extension__ __PRETTY_FUNCTION__
))
;
4735
4736 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4737 if (Info.noteFailure()) {
4738 MemberPtr MemPtr;
4739 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4740 }
4741 return nullptr;
4742 }
4743
4744 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4745 BO->getRHS(), IncludeMember);
4746}
4747
4748/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4749/// the provided lvalue, which currently refers to the base object.
4750static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4751 LValue &Result) {
4752 SubobjectDesignator &D = Result.Designator;
4753 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4754 return false;
4755
4756 QualType TargetQT = E->getType();
4757 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4758 TargetQT = PT->getPointeeType();
4759
4760 // Check this cast lands within the final derived-to-base subobject path.
4761 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4762 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4763 << D.MostDerivedType << TargetQT;
4764 return false;
4765 }
4766
4767 // Check the type of the final cast. We don't need to check the path,
4768 // since a cast can only be formed if the path is unique.
4769 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4770 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4771 const CXXRecordDecl *FinalType;
4772 if (NewEntriesSize == D.MostDerivedPathLength)
4773 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4774 else
4775 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4776 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4777 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4778 << D.MostDerivedType << TargetQT;
4779 return false;
4780 }
4781
4782 // Truncate the lvalue to the appropriate derived class.
4783 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4784}
4785
4786/// Get the value to use for a default-initialized object of type T.
4787/// Return false if it encounters something invalid.
4788static bool getDefaultInitValue(QualType T, APValue &Result) {
4789 bool Success = true;
4790 if (auto *RD = T->getAsCXXRecordDecl()) {
4791 if (RD->isInvalidDecl()) {
4792 Result = APValue();
4793 return false;
4794 }
4795 if (RD->isUnion()) {
4796 Result = APValue((const FieldDecl *)nullptr);
4797 return true;
4798 }
4799 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4800 std::distance(RD->field_begin(), RD->field_end()));
4801
4802 unsigned Index = 0;
4803 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4804 End = RD->bases_end();
4805 I != End; ++I, ++Index)
4806 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4807
4808 for (const auto *I : RD->fields()) {
4809 if (I->isUnnamedBitfield())
4810 continue;
4811 Success &= getDefaultInitValue(I->getType(),
4812 Result.getStructField(I->getFieldIndex()));
4813 }
4814 return Success;
4815 }
4816
4817 if (auto *AT =
4818 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4819 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4820 if (Result.hasArrayFiller())
4821 Success &=
4822 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4823
4824 return Success;
4825 }
4826
4827 Result = APValue::IndeterminateValue();
4828 return true;
4829}
4830
4831namespace {
4832enum EvalStmtResult {
4833 /// Evaluation failed.
4834 ESR_Failed,
4835 /// Hit a 'return' statement.
4836 ESR_Returned,
4837 /// Evaluation succeeded.
4838 ESR_Succeeded,
4839 /// Hit a 'continue' statement.
4840 ESR_Continue,
4841 /// Hit a 'break' statement.
4842 ESR_Break,
4843 /// Still scanning for 'case' or 'default' statement.
4844 ESR_CaseNotFound
4845};
4846}
4847
4848static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4849 if (VD->isInvalidDecl())
4850 return false;
4851 // We don't need to evaluate the initializer for a static local.
4852 if (!VD->hasLocalStorage())
4853 return true;
4854
4855 LValue Result;
4856 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4857 ScopeKind::Block, Result);
4858
4859 const Expr *InitE = VD->getInit();
4860 if (!InitE) {
4861 if (VD->getType()->isDependentType())
4862 return Info.noteSideEffect();
4863 return getDefaultInitValue(VD->getType(), Val);
4864 }
4865 if (InitE->isValueDependent())
4866 return false;
4867
4868 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4869 // Wipe out any partially-computed value, to allow tracking that this
4870 // evaluation failed.
4871 Val = APValue();
4872 return false;
4873 }
4874
4875 return true;
4876}
4877
4878static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4879 bool OK = true;
4880
4881 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4882 OK &= EvaluateVarDecl(Info, VD);
4883
4884 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4885 for (auto *BD : DD->bindings())
4886 if (auto *VD = BD->getHoldingVar())
4887 OK &= EvaluateDecl(Info, VD);
4888
4889 return OK;
4890}
4891
4892static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4893 assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void (
0) : __assert_fail ("E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 4893, __extension__ __PRETTY_FUNCTION__))
;
4894 if (Info.noteSideEffect())
4895 return true;
4896 assert(E->containsErrors() && "valid value-dependent expression should never "(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never "
"reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\""
, "clang/lib/AST/ExprConstant.cpp", 4897, __extension__ __PRETTY_FUNCTION__
))
4897 "reach invalid code path.")(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never "
"reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\""
, "clang/lib/AST/ExprConstant.cpp", 4897, __extension__ __PRETTY_FUNCTION__
))
;
4898 return false;
4899}
4900
4901/// Evaluate a condition (either a variable declaration or an expression).
4902static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4903 const Expr *Cond, bool &Result) {
4904 if (Cond->isValueDependent())
4905 return false;
4906 FullExpressionRAII Scope(Info);
4907 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4908 return false;
4909 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4910 return false;
4911 return Scope.destroy();
4912}
4913
4914namespace {
4915/// A location where the result (returned value) of evaluating a
4916/// statement should be stored.
4917struct StmtResult {
4918 /// The APValue that should be filled in with the returned value.
4919 APValue &Value;
4920 /// The location containing the result, if any (used to support RVO).
4921 const LValue *Slot;
4922};
4923
4924struct TempVersionRAII {
4925 CallStackFrame &Frame;
4926
4927 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4928 Frame.pushTempVersion();
4929 }
4930
4931 ~TempVersionRAII() {
4932 Frame.popTempVersion();
4933 }
4934};
4935
4936}
4937
4938static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4939 const Stmt *S,
4940 const SwitchCase *SC = nullptr);
4941
4942/// Evaluate the body of a loop, and translate the result as appropriate.
4943static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4944 const Stmt *Body,
4945 const SwitchCase *Case = nullptr) {
4946 BlockScopeRAII Scope(Info);
4947
4948 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4949 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4950 ESR = ESR_Failed;
4951
4952 switch (ESR) {
4953 case ESR_Break:
4954 return ESR_Succeeded;
4955 case ESR_Succeeded:
4956 case ESR_Continue:
4957 return ESR_Continue;
4958 case ESR_Failed:
4959 case ESR_Returned:
4960 case ESR_CaseNotFound:
4961 return ESR;
4962 }
4963 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 4963)
;
4964}
4965
4966/// Evaluate a switch statement.
4967static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4968 const SwitchStmt *SS) {
4969 BlockScopeRAII Scope(Info);
4970
4971 // Evaluate the switch condition.
4972 APSInt Value;
4973 {
4974 if (const Stmt *Init = SS->getInit()) {
4975 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4976 if (ESR != ESR_Succeeded) {
4977 if (ESR != ESR_Failed && !Scope.destroy())
4978 ESR = ESR_Failed;
4979 return ESR;
4980 }
4981 }
4982
4983 FullExpressionRAII CondScope(Info);
4984 if (SS->getConditionVariable() &&
4985 !EvaluateDecl(Info, SS->getConditionVariable()))
4986 return ESR_Failed;
4987 if (SS->getCond()->isValueDependent()) {
4988 if (!EvaluateDependentExpr(SS->getCond(), Info))
4989 return ESR_Failed;
4990 } else {
4991 if (!EvaluateInteger(SS->getCond(), Value, Info))
4992 return ESR_Failed;
4993 }
4994 if (!CondScope.destroy())
4995 return ESR_Failed;
4996 }
4997
4998 // Find the switch case corresponding to the value of the condition.
4999 // FIXME: Cache this lookup.
5000 const SwitchCase *Found = nullptr;
5001 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5002 SC = SC->getNextSwitchCase()) {
5003 if (isa<DefaultStmt>(SC)) {
5004 Found = SC;
5005 continue;
5006 }
5007
5008 const CaseStmt *CS = cast<CaseStmt>(SC);
5009 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5010 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5011 : LHS;
5012 if (LHS <= Value && Value <= RHS) {
5013 Found = SC;
5014 break;
5015 }
5016 }
5017
5018 if (!Found)
5019 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5020
5021 // Search the switch body for the switch case and evaluate it from there.
5022 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5023 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5024 return ESR_Failed;
5025
5026 switch (ESR) {
5027 case ESR_Break:
5028 return ESR_Succeeded;
5029 case ESR_Succeeded:
5030 case ESR_Continue:
5031 case ESR_Failed:
5032 case ESR_Returned:
5033 return ESR;
5034 case ESR_CaseNotFound:
5035 // This can only happen if the switch case is nested within a statement
5036 // expression. We have no intention of supporting that.
5037 Info.FFDiag(Found->getBeginLoc(),
5038 diag::note_constexpr_stmt_expr_unsupported);
5039 return ESR_Failed;
5040 }
5041 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 5041)
;
5042}
5043
5044static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5045 // An expression E is a core constant expression unless the evaluation of E
5046 // would evaluate one of the following: [C++23] - a control flow that passes
5047 // through a declaration of a variable with static or thread storage duration
5048 // unless that variable is usable in constant expressions.
5049 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5050 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5051 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5052 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5053 return false;
5054 }
5055 return true;
5056}
5057
5058// Evaluate a statement.
5059static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5060 const Stmt *S, const SwitchCase *Case) {
5061 if (!Info.nextStep(S))
5062 return ESR_Failed;
5063
5064 // If we're hunting down a 'case' or 'default' label, recurse through
5065 // substatements until we hit the label.
5066 if (Case) {
5067 switch (S->getStmtClass()) {
5068 case Stmt::CompoundStmtClass:
5069 // FIXME: Precompute which substatement of a compound statement we
5070 // would jump to, and go straight there rather than performing a
5071 // linear scan each time.
5072 case Stmt::LabelStmtClass:
5073 case Stmt::AttributedStmtClass:
5074 case Stmt::DoStmtClass:
5075 break;
5076
5077 case Stmt::CaseStmtClass:
5078 case Stmt::DefaultStmtClass:
5079 if (Case == S)
5080 Case = nullptr;
5081 break;
5082
5083 case Stmt::IfStmtClass: {
5084 // FIXME: Precompute which side of an 'if' we would jump to, and go
5085 // straight there rather than scanning both sides.
5086 const IfStmt *IS = cast<IfStmt>(S);
5087
5088 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5089 // preceded by our switch label.
5090 BlockScopeRAII Scope(Info);
5091
5092 // Step into the init statement in case it brings an (uninitialized)
5093 // variable into scope.
5094 if (const Stmt *Init = IS->getInit()) {
5095 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5096 if (ESR != ESR_CaseNotFound) {
5097 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5097, __extension__ __PRETTY_FUNCTION__))
;
5098 return ESR;
5099 }
5100 }
5101
5102 // Condition variable must be initialized if it exists.
5103 // FIXME: We can skip evaluating the body if there's a condition
5104 // variable, as there can't be any case labels within it.
5105 // (The same is true for 'for' statements.)
5106
5107 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5108 if (ESR == ESR_Failed)
5109 return ESR;
5110 if (ESR != ESR_CaseNotFound)
5111 return Scope.destroy() ? ESR : ESR_Failed;
5112 if (!IS->getElse())
5113 return ESR_CaseNotFound;
5114
5115 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5116 if (ESR == ESR_Failed)
5117 return ESR;
5118 if (ESR != ESR_CaseNotFound)
5119 return Scope.destroy() ? ESR : ESR_Failed;
5120 return ESR_CaseNotFound;
5121 }
5122
5123 case Stmt::WhileStmtClass: {
5124 EvalStmtResult ESR =
5125 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5126 if (ESR != ESR_Continue)
5127 return ESR;
5128 break;
5129 }
5130
5131 case Stmt::ForStmtClass: {
5132 const ForStmt *FS = cast<ForStmt>(S);
5133 BlockScopeRAII Scope(Info);
5134
5135 // Step into the init statement in case it brings an (uninitialized)
5136 // variable into scope.
5137 if (const Stmt *Init = FS->getInit()) {
5138 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5139 if (ESR != ESR_CaseNotFound) {
5140 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5140, __extension__ __PRETTY_FUNCTION__))
;
5141 return ESR;
5142 }
5143 }
5144
5145 EvalStmtResult ESR =
5146 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5147 if (ESR != ESR_Continue)
5148 return ESR;
5149 if (const auto *Inc = FS->getInc()) {
5150 if (Inc->isValueDependent()) {
5151 if (!EvaluateDependentExpr(Inc, Info))
5152 return ESR_Failed;
5153 } else {
5154 FullExpressionRAII IncScope(Info);
5155 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5156 return ESR_Failed;
5157 }
5158 }
5159 break;
5160 }
5161
5162 case Stmt::DeclStmtClass: {
5163 // Start the lifetime of any uninitialized variables we encounter. They
5164 // might be used by the selected branch of the switch.
5165 const DeclStmt *DS = cast<DeclStmt>(S);
5166 for (const auto *D : DS->decls()) {
5167 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5168 if (!CheckLocalVariableDeclaration(Info, VD))
5169 return ESR_Failed;
5170 if (VD->hasLocalStorage() && !VD->getInit())
5171 if (!EvaluateVarDecl(Info, VD))
5172 return ESR_Failed;
5173 // FIXME: If the variable has initialization that can't be jumped
5174 // over, bail out of any immediately-surrounding compound-statement
5175 // too. There can't be any case labels here.
5176 }
5177 }
5178 return ESR_CaseNotFound;
5179 }
5180
5181 default:
5182 return ESR_CaseNotFound;
5183 }
5184 }
5185
5186 switch (S->getStmtClass()) {
5187 default:
5188 if (const Expr *E = dyn_cast<Expr>(S)) {
5189 if (E->isValueDependent()) {
5190 if (!EvaluateDependentExpr(E, Info))
5191 return ESR_Failed;
5192 } else {
5193 // Don't bother evaluating beyond an expression-statement which couldn't
5194 // be evaluated.
5195 // FIXME: Do we need the FullExpressionRAII object here?
5196 // VisitExprWithCleanups should create one when necessary.
5197 FullExpressionRAII Scope(Info);
5198 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5199 return ESR_Failed;
5200 }
5201 return ESR_Succeeded;
5202 }
5203
5204 Info.FFDiag(S->getBeginLoc());
5205 return ESR_Failed;
5206
5207 case Stmt::NullStmtClass:
5208 return ESR_Succeeded;
5209
5210 case Stmt::DeclStmtClass: {
5211 const DeclStmt *DS = cast<DeclStmt>(S);
5212 for (const auto *D : DS->decls()) {
5213 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5214 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5215 return ESR_Failed;
5216 // Each declaration initialization is its own full-expression.
5217 FullExpressionRAII Scope(Info);
5218 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5219 return ESR_Failed;
5220 if (!Scope.destroy())
5221 return ESR_Failed;
5222 }
5223 return ESR_Succeeded;
5224 }
5225
5226 case Stmt::ReturnStmtClass: {
5227 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5228 FullExpressionRAII Scope(Info);
5229 if (RetExpr && RetExpr->isValueDependent()) {
5230 EvaluateDependentExpr(RetExpr, Info);
5231 // We know we returned, but we don't know what the value is.
5232 return ESR_Failed;
5233 }
5234 if (RetExpr &&
5235 !(Result.Slot
5236 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5237 : Evaluate(Result.Value, Info, RetExpr)))
5238 return ESR_Failed;
5239 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5240 }
5241
5242 case Stmt::CompoundStmtClass: {
5243 BlockScopeRAII Scope(Info);
5244
5245 const CompoundStmt *CS = cast<CompoundStmt>(S);
5246 for (const auto *BI : CS->body()) {
5247 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5248 if (ESR == ESR_Succeeded)
5249 Case = nullptr;
5250 else if (ESR != ESR_CaseNotFound) {
5251 if (ESR != ESR_Failed && !Scope.destroy())
5252 return ESR_Failed;
5253 return ESR;
5254 }
5255 }
5256 if (Case)
5257 return ESR_CaseNotFound;
5258 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5259 }
5260
5261 case Stmt::IfStmtClass: {
5262 const IfStmt *IS = cast<IfStmt>(S);
5263
5264 // Evaluate the condition, as either a var decl or as an expression.
5265 BlockScopeRAII Scope(Info);
5266 if (const Stmt *Init = IS->getInit()) {
5267 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5268 if (ESR != ESR_Succeeded) {
5269 if (ESR != ESR_Failed && !Scope.destroy())
5270 return ESR_Failed;
5271 return ESR;
5272 }
5273 }
5274 bool Cond;
5275 if (IS->isConsteval()) {
5276 Cond = IS->isNonNegatedConsteval();
5277 // If we are not in a constant context, if consteval should not evaluate
5278 // to true.
5279 if (!Info.InConstantContext)
5280 Cond = !Cond;
5281 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5282 Cond))
5283 return ESR_Failed;
5284
5285 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5286 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5287 if (ESR != ESR_Succeeded) {
5288 if (ESR != ESR_Failed && !Scope.destroy())
5289 return ESR_Failed;
5290 return ESR;
5291 }
5292 }
5293 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5294 }
5295
5296 case Stmt::WhileStmtClass: {
5297 const WhileStmt *WS = cast<WhileStmt>(S);
5298 while (true) {
5299 BlockScopeRAII Scope(Info);
5300 bool Continue;
5301 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5302 Continue))
5303 return ESR_Failed;
5304 if (!Continue)
5305 break;
5306
5307 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5308 if (ESR != ESR_Continue) {
5309 if (ESR != ESR_Failed && !Scope.destroy())
5310 return ESR_Failed;
5311 return ESR;
5312 }
5313 if (!Scope.destroy())
5314 return ESR_Failed;
5315 }
5316 return ESR_Succeeded;
5317 }
5318
5319 case Stmt::DoStmtClass: {
5320 const DoStmt *DS = cast<DoStmt>(S);
5321 bool Continue;
5322 do {
5323 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5324 if (ESR != ESR_Continue)
5325 return ESR;
5326 Case = nullptr;
5327
5328 if (DS->getCond()->isValueDependent()) {
5329 EvaluateDependentExpr(DS->getCond(), Info);
5330 // Bailout as we don't know whether to keep going or terminate the loop.
5331 return ESR_Failed;
5332 }
5333 FullExpressionRAII CondScope(Info);
5334 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5335 !CondScope.destroy())
5336 return ESR_Failed;
5337 } while (Continue);
5338 return ESR_Succeeded;
5339 }
5340
5341 case Stmt::ForStmtClass: {
5342 const ForStmt *FS = cast<ForStmt>(S);
5343 BlockScopeRAII ForScope(Info);
5344 if (FS->getInit()) {
5345 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5346 if (ESR != ESR_Succeeded) {
5347 if (ESR != ESR_Failed && !ForScope.destroy())
5348 return ESR_Failed;
5349 return ESR;
5350 }
5351 }
5352 while (true) {
5353 BlockScopeRAII IterScope(Info);
5354 bool Continue = true;
5355 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5356 FS->getCond(), Continue))
5357 return ESR_Failed;
5358 if (!Continue)
5359 break;
5360
5361 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5362 if (ESR != ESR_Continue) {
5363 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5364 return ESR_Failed;
5365 return ESR;
5366 }
5367
5368 if (const auto *Inc = FS->getInc()) {
5369 if (Inc->isValueDependent()) {
5370 if (!EvaluateDependentExpr(Inc, Info))
5371 return ESR_Failed;
5372 } else {
5373 FullExpressionRAII IncScope(Info);
5374 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5375 return ESR_Failed;
5376 }
5377 }
5378
5379 if (!IterScope.destroy())
5380 return ESR_Failed;
5381 }
5382 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5383 }
5384
5385 case Stmt::CXXForRangeStmtClass: {
5386 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5387 BlockScopeRAII Scope(Info);
5388
5389 // Evaluate the init-statement if present.
5390 if (FS->getInit()) {
5391 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5392 if (ESR != ESR_Succeeded) {
5393 if (ESR != ESR_Failed && !Scope.destroy())
5394 return ESR_Failed;
5395 return ESR;
5396 }
5397 }
5398
5399 // Initialize the __range variable.
5400 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5401 if (ESR != ESR_Succeeded) {
5402 if (ESR != ESR_Failed && !Scope.destroy())
5403 return ESR_Failed;
5404 return ESR;
5405 }
5406
5407 // In error-recovery cases it's possible to get here even if we failed to
5408 // synthesize the __begin and __end variables.
5409 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5410 return ESR_Failed;
5411
5412 // Create the __begin and __end iterators.
5413 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 return ESR_Failed;
5417 return ESR;
5418 }
5419 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5420 if (ESR != ESR_Succeeded) {
5421 if (ESR != ESR_Failed && !Scope.destroy())
5422 return ESR_Failed;
5423 return ESR;
5424 }
5425
5426 while (true) {
5427 // Condition: __begin != __end.
5428 {
5429 if (FS->getCond()->isValueDependent()) {
5430 EvaluateDependentExpr(FS->getCond(), Info);
5431 // We don't know whether to keep going or terminate the loop.
5432 return ESR_Failed;
5433 }
5434 bool Continue = true;
5435 FullExpressionRAII CondExpr(Info);
5436 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5437 return ESR_Failed;
5438 if (!Continue)
5439 break;
5440 }
5441
5442 // User's variable declaration, initialized by *__begin.
5443 BlockScopeRAII InnerScope(Info);
5444 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5445 if (ESR != ESR_Succeeded) {
5446 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5447 return ESR_Failed;
5448 return ESR;
5449 }
5450
5451 // Loop body.
5452 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5453 if (ESR != ESR_Continue) {
5454 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5455 return ESR_Failed;
5456 return ESR;
5457 }
5458 if (FS->getInc()->isValueDependent()) {
5459 if (!EvaluateDependentExpr(FS->getInc(), Info))
5460 return ESR_Failed;
5461 } else {
5462 // Increment: ++__begin
5463 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5464 return ESR_Failed;
5465 }
5466
5467 if (!InnerScope.destroy())
5468 return ESR_Failed;
5469 }
5470
5471 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5472 }
5473
5474 case Stmt::SwitchStmtClass:
5475 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5476
5477 case Stmt::ContinueStmtClass:
5478 return ESR_Continue;
5479
5480 case Stmt::BreakStmtClass:
5481 return ESR_Break;
5482
5483 case Stmt::LabelStmtClass:
5484 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5485
5486 case Stmt::AttributedStmtClass:
5487 // As a general principle, C++11 attributes can be ignored without
5488 // any semantic impact.
5489 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5490 Case);
5491
5492 case Stmt::CaseStmtClass:
5493 case Stmt::DefaultStmtClass:
5494 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5495 case Stmt::CXXTryStmtClass:
5496 // Evaluate try blocks by evaluating all sub statements.
5497 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5498 }
5499}
5500
5501/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5502/// default constructor. If so, we'll fold it whether or not it's marked as
5503/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5504/// so we need special handling.
5505static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5506 const CXXConstructorDecl *CD,
5507 bool IsValueInitialization) {
5508 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5509 return false;
5510
5511 // Value-initialization does not call a trivial default constructor, so such a
5512 // call is a core constant expression whether or not the constructor is
5513 // constexpr.
5514 if (!CD->isConstexpr() && !IsValueInitialization) {
5515 if (Info.getLangOpts().CPlusPlus11) {
5516 // FIXME: If DiagDecl is an implicitly-declared special member function,
5517 // we should be much more explicit about why it's not constexpr.
5518 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5519 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5520 Info.Note(CD->getLocation(), diag::note_declared_at);
5521 } else {
5522 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5523 }
5524 }
5525 return true;
5526}
5527
5528/// CheckConstexprFunction - Check that a function can be called in a constant
5529/// expression.
5530static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5531 const FunctionDecl *Declaration,
5532 const FunctionDecl *Definition,
5533 const Stmt *Body) {
5534 // Potential constant expressions can contain calls to declared, but not yet
5535 // defined, constexpr functions.
5536 if (Info.checkingPotentialConstantExpression() && !Definition &&
5537 Declaration->isConstexpr())
5538 return false;
5539
5540 // Bail out if the function declaration itself is invalid. We will
5541 // have produced a relevant diagnostic while parsing it, so just
5542 // note the problematic sub-expression.
5543 if (Declaration->isInvalidDecl()) {
5544 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5545 return false;
5546 }
5547
5548 // DR1872: An instantiated virtual constexpr function can't be called in a
5549 // constant expression (prior to C++20). We can still constant-fold such a
5550 // call.
5551 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5552 cast<CXXMethodDecl>(Declaration)->isVirtual())
5553 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5554
5555 if (Definition && Definition->isInvalidDecl()) {
5556 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5557 return false;
5558 }
5559
5560 // Can we evaluate this function call?
5561 if (Definition && Definition->isConstexpr() && Body)
5562 return true;
5563
5564 if (Info.getLangOpts().CPlusPlus11) {
5565 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5566
5567 // If this function is not constexpr because it is an inherited
5568 // non-constexpr constructor, diagnose that directly.
5569 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5570 if (CD && CD->isInheritingConstructor()) {
5571 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5572 if (!Inherited->isConstexpr())
5573 DiagDecl = CD = Inherited;
5574 }
5575
5576 // FIXME: If DiagDecl is an implicitly-declared special member function
5577 // or an inheriting constructor, we should be much more explicit about why
5578 // it's not constexpr.
5579 if (CD && CD->isInheritingConstructor())
5580 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5581 << CD->getInheritedConstructor().getConstructor()->getParent();
5582 else
5583 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5584 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5585 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5586 } else {
5587 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5588 }
5589 return false;
5590}
5591
5592namespace {
5593struct CheckDynamicTypeHandler {
5594 AccessKinds AccessKind;
5595 typedef bool result_type;
5596 bool failed() { return false; }
5597 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5598 bool found(APSInt &Value, QualType SubobjType) { return true; }
5599 bool found(APFloat &Value, QualType SubobjType) { return true; }
5600};
5601} // end anonymous namespace
5602
5603/// Check that we can access the notional vptr of an object / determine its
5604/// dynamic type.
5605static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5606 AccessKinds AK, bool Polymorphic) {
5607 if (This.Designator.Invalid)
5608 return false;
5609
5610 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5611
5612 if (!Obj)
5613 return false;
5614
5615 if (!Obj.Value) {
5616 // The object is not usable in constant expressions, so we can't inspect
5617 // its value to see if it's in-lifetime or what the active union members
5618 // are. We can still check for a one-past-the-end lvalue.
5619 if (This.Designator.isOnePastTheEnd() ||
5620 This.Designator.isMostDerivedAnUnsizedArray()) {
5621 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5622 ? diag::note_constexpr_access_past_end
5623 : diag::note_constexpr_access_unsized_array)
5624 << AK;
5625 return false;
5626 } else if (Polymorphic) {
5627 // Conservatively refuse to perform a polymorphic operation if we would
5628 // not be able to read a notional 'vptr' value.
5629 APValue Val;
5630 This.moveInto(Val);
5631 QualType StarThisType =
5632 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5633 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5634 << AK << Val.getAsString(Info.Ctx, StarThisType);
5635 return false;
5636 }
5637 return true;
5638 }
5639
5640 CheckDynamicTypeHandler Handler{AK};
5641 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5642}
5643
5644/// Check that the pointee of the 'this' pointer in a member function call is
5645/// either within its lifetime or in its period of construction or destruction.
5646static bool
5647checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5648 const LValue &This,
5649 const CXXMethodDecl *NamedMember) {
5650 return checkDynamicType(
5651 Info, E, This,
5652 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5653}
5654
5655struct DynamicType {
5656 /// The dynamic class type of the object.
5657 const CXXRecordDecl *Type;
5658 /// The corresponding path length in the lvalue.
5659 unsigned PathLength;
5660};
5661
5662static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5663 unsigned PathLength) {
5664 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength
&& PathLength <= Designator.Entries.size() &&
"invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "clang/lib/AST/ExprConstant.cpp", 5665, __extension__ __PRETTY_FUNCTION__
))
5665 Designator.Entries.size() && "invalid path length")(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength
&& PathLength <= Designator.Entries.size() &&
"invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "clang/lib/AST/ExprConstant.cpp", 5665, __extension__ __PRETTY_FUNCTION__
))
;
5666 return (PathLength == Designator.MostDerivedPathLength)
5667 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5668 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5669}
5670
5671/// Determine the dynamic type of an object.
5672static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5673 const Expr *E,
5674 LValue &This,
5675 AccessKinds AK) {
5676 // If we don't have an lvalue denoting an object of class type, there is no
5677 // meaningful dynamic type. (We consider objects of non-class type to have no
5678 // dynamic type.)
5679 if (!checkDynamicType(Info, E, This, AK, true))
5680 return std::nullopt;
5681
5682 // Refuse to compute a dynamic type in the presence of virtual bases. This
5683 // shouldn't happen other than in constant-folding situations, since literal
5684 // types can't have virtual bases.
5685 //
5686 // Note that consumers of DynamicType assume that the type has no virtual
5687 // bases, and will need modifications if this restriction is relaxed.
5688 const CXXRecordDecl *Class =
5689 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5690 if (!Class || Class->getNumVBases()) {
5691 Info.FFDiag(E);
5692 return std::nullopt;
5693 }
5694
5695 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5696 // binary search here instead. But the overwhelmingly common case is that
5697 // we're not in the middle of a constructor, so it probably doesn't matter
5698 // in practice.
5699 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5700 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5701 PathLength <= Path.size(); ++PathLength) {
5702 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5703 Path.slice(0, PathLength))) {
5704 case ConstructionPhase::Bases:
5705 case ConstructionPhase::DestroyingBases:
5706 // We're constructing or destroying a base class. This is not the dynamic
5707 // type.
5708 break;
5709
5710 case ConstructionPhase::None:
5711 case ConstructionPhase::AfterBases:
5712 case ConstructionPhase::AfterFields:
5713 case ConstructionPhase::Destroying:
5714 // We've finished constructing the base classes and not yet started
5715 // destroying them again, so this is the dynamic type.
5716 return DynamicType{getBaseClassType(This.Designator, PathLength),
5717 PathLength};
5718 }
5719 }
5720
5721 // CWG issue 1517: we're constructing a base class of the object described by
5722 // 'This', so that object has not yet begun its period of construction and
5723 // any polymorphic operation on it results in undefined behavior.
5724 Info.FFDiag(E);
5725 return std::nullopt;
5726}
5727
5728/// Perform virtual dispatch.
5729static const CXXMethodDecl *HandleVirtualDispatch(
5730 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5731 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5732 std::optional<DynamicType> DynType = ComputeDynamicType(
5733 Info, E, This,
5734 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5735 if (!DynType)
5736 return nullptr;
5737
5738 // Find the final overrider. It must be declared in one of the classes on the
5739 // path from the dynamic type to the static type.
5740 // FIXME: If we ever allow literal types to have virtual base classes, that
5741 // won't be true.
5742 const CXXMethodDecl *Callee = Found;
5743 unsigned PathLength = DynType->PathLength;
5744 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5745 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5746 const CXXMethodDecl *Overrider =
5747 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5748 if (Overrider) {
5749 Callee = Overrider;
5750 break;
5751 }
5752 }
5753
5754 // C++2a [class.abstract]p6:
5755 // the effect of making a virtual call to a pure virtual function [...] is
5756 // undefined
5757 if (Callee->isPure()) {
5758 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5759 Info.Note(Callee->getLocation(), diag::note_declared_at);
5760 return nullptr;
5761 }
5762
5763 // If necessary, walk the rest of the path to determine the sequence of
5764 // covariant adjustment steps to apply.
5765 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5766 Found->getReturnType())) {
5767 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5768 for (unsigned CovariantPathLength = PathLength + 1;
5769 CovariantPathLength != This.Designator.Entries.size();
5770 ++CovariantPathLength) {
5771 const CXXRecordDecl *NextClass =
5772 getBaseClassType(This.Designator, CovariantPathLength);
5773 const CXXMethodDecl *Next =
5774 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5775 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5776 Next->getReturnType(), CovariantAdjustmentPath.back()))
5777 CovariantAdjustmentPath.push_back(Next->getReturnType());
5778 }
5779 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5780 CovariantAdjustmentPath.back()))
5781 CovariantAdjustmentPath.push_back(Found->getReturnType());
5782 }
5783
5784 // Perform 'this' adjustment.
5785 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5786 return nullptr;
5787
5788 return Callee;
5789}
5790
5791/// Perform the adjustment from a value returned by a virtual function to
5792/// a value of the statically expected type, which may be a pointer or
5793/// reference to a base class of the returned type.
5794static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5795 APValue &Result,
5796 ArrayRef<QualType> Path) {
5797 assert(Result.isLValue() &&(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5798, __extension__ __PRETTY_FUNCTION__
))
5798 "unexpected kind of APValue for covariant return")(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5798, __extension__ __PRETTY_FUNCTION__
))
;
5799 if (Result.isNullPointer())
5800 return true;
5801
5802 LValue LVal;
5803 LVal.setFrom(Info.Ctx, Result);
5804
5805 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5806 for (unsigned I = 1; I != Path.size(); ++I) {
5807 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5808 assert(OldClass && NewClass && "unexpected kind of covariant return")(static_cast <bool> (OldClass && NewClass &&
"unexpected kind of covariant return") ? void (0) : __assert_fail
("OldClass && NewClass && \"unexpected kind of covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5808, __extension__ __PRETTY_FUNCTION__
))
;
5809 if (OldClass != NewClass &&
5810 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5811 return false;
5812 OldClass = NewClass;
5813 }
5814
5815 LVal.moveInto(Result);
5816 return true;
5817}
5818
5819/// Determine whether \p Base, which is known to be a direct base class of
5820/// \p Derived, is a public base class.
5821static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5822 const CXXRecordDecl *Base) {
5823 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5824 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5825 if (BaseClass && declaresSameEntity(BaseClass, Base))
5826 return BaseSpec.getAccessSpecifier() == AS_public;
5827 }
5828 llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived"
, "clang/lib/AST/ExprConstant.cpp", 5828)
;
5829}
5830
5831/// Apply the given dynamic cast operation on the provided lvalue.
5832///
5833/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5834/// to find a suitable target subobject.
5835static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5836 LValue &Ptr) {
5837 // We can't do anything with a non-symbolic pointer value.
5838 SubobjectDesignator &D = Ptr.Designator;
5839 if (D.Invalid)
5840 return false;
5841
5842 // C++ [expr.dynamic.cast]p6:
5843 // If v is a null pointer value, the result is a null pointer value.
5844 if (Ptr.isNullPointer() && !E->isGLValue())
5845 return true;
5846
5847 // For all the other cases, we need the pointer to point to an object within
5848 // its lifetime / period of construction / destruction, and we need to know
5849 // its dynamic type.
5850 std::optional<DynamicType> DynType =
5851 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5852 if (!DynType)
5853 return false;
5854
5855 // C++ [expr.dynamic.cast]p7:
5856 // If T is "pointer to cv void", then the result is a pointer to the most
5857 // derived object
5858 if (E->getType()->isVoidPointerType())
5859 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5860
5861 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5862 assert(C && "dynamic_cast target is not void pointer nor class")(static_cast <bool> (C && "dynamic_cast target is not void pointer nor class"
) ? void (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\""
, "clang/lib/AST/ExprConstant.cpp", 5862, __extension__ __PRETTY_FUNCTION__
))
;
5863 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5864
5865 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5866 // C++ [expr.dynamic.cast]p9:
5867 if (!E->isGLValue()) {
5868 // The value of a failed cast to pointer type is the null pointer value
5869 // of the required result type.
5870 Ptr.setNull(Info.Ctx, E->getType());
5871 return true;
5872 }
5873
5874 // A failed cast to reference type throws [...] std::bad_cast.
5875 unsigned DiagKind;
5876 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5877 DynType->Type->isDerivedFrom(C)))
5878 DiagKind = 0;
5879 else if (!Paths || Paths->begin() == Paths->end())
5880 DiagKind = 1;
5881 else if (Paths->isAmbiguous(CQT))
5882 DiagKind = 2;
5883 else {
5884 assert(Paths->front().Access != AS_public && "why did the cast fail?")(static_cast <bool> (Paths->front().Access != AS_public
&& "why did the cast fail?") ? void (0) : __assert_fail
("Paths->front().Access != AS_public && \"why did the cast fail?\""
, "clang/lib/AST/ExprConstant.cpp", 5884, __extension__ __PRETTY_FUNCTION__
))
;
5885 DiagKind = 3;
5886 }
5887 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5888 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5889 << Info.Ctx.getRecordType(DynType->Type)
5890 << E->getType().getUnqualifiedType();
5891 return false;
5892 };
5893
5894 // Runtime check, phase 1:
5895 // Walk from the base subobject towards the derived object looking for the
5896 // target type.
5897 for (int PathLength = Ptr.Designator.Entries.size();
5898 PathLength >= (int)DynType->PathLength; --PathLength) {
5899 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5900 if (declaresSameEntity(Class, C))
5901 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5902 // We can only walk across public inheritance edges.
5903 if (PathLength > (int)DynType->PathLength &&
5904 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5905 Class))
5906 return RuntimeCheckFailed(nullptr);
5907 }
5908
5909 // Runtime check, phase 2:
5910 // Search the dynamic type for an unambiguous public base of type C.
5911 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5912 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5913 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5914 Paths.front().Access == AS_public) {
5915 // Downcast to the dynamic type...
5916 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5917 return false;
5918 // ... then upcast to the chosen base class subobject.
5919 for (CXXBasePathElement &Elem : Paths.front())
5920 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5921 return false;
5922 return true;
5923 }
5924
5925 // Otherwise, the runtime check fails.
5926 return RuntimeCheckFailed(&Paths);
5927}
5928
5929namespace {
5930struct StartLifetimeOfUnionMemberHandler {
5931 EvalInfo &Info;
5932 const Expr *LHSExpr;
5933 const FieldDecl *Field;
5934 bool DuringInit;
5935 bool Failed = false;
5936 static const AccessKinds AccessKind = AK_Assign;
5937
5938 typedef bool result_type;
5939 bool failed() { return Failed; }
5940 bool found(APValue &Subobj, QualType SubobjType) {
5941 // We are supposed to perform no initialization but begin the lifetime of
5942 // the object. We interpret that as meaning to do what default
5943 // initialization of the object would do if all constructors involved were
5944 // trivial:
5945 // * All base, non-variant member, and array element subobjects' lifetimes
5946 // begin
5947 // * No variant members' lifetimes begin
5948 // * All scalar subobjects whose lifetimes begin have indeterminate values
5949 assert(SubobjType->isUnionType())(static_cast <bool> (SubobjType->isUnionType()) ? void
(0) : __assert_fail ("SubobjType->isUnionType()", "clang/lib/AST/ExprConstant.cpp"
, 5949, __extension__ __PRETTY_FUNCTION__))
;
5950 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5951 // This union member is already active. If it's also in-lifetime, there's
5952 // nothing to do.
5953 if (Subobj.getUnionValue().hasValue())
5954 return true;
5955 } else if (DuringInit) {
5956 // We're currently in the process of initializing a different union
5957 // member. If we carried on, that initialization would attempt to
5958 // store to an inactive union member, resulting in undefined behavior.
5959 Info.FFDiag(LHSExpr,
5960 diag::note_constexpr_union_member_change_during_init);
5961 return false;
5962 }
5963 APValue Result;
5964 Failed = !getDefaultInitValue(Field->getType(), Result);
5965 Subobj.setUnion(Field, Result);
5966 return true;
5967 }
5968 bool found(APSInt &Value, QualType SubobjType) {
5969 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "clang/lib/AST/ExprConstant.cpp", 5969)
;
5970 }
5971 bool found(APFloat &Value, QualType SubobjType) {
5972 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "clang/lib/AST/ExprConstant.cpp", 5972)
;
5973 }
5974};
5975} // end anonymous namespace
5976
5977const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5978
5979/// Handle a builtin simple-assignment or a call to a trivial assignment
5980/// operator whose left-hand side might involve a union member access. If it
5981/// does, implicitly start the lifetime of any accessed union elements per
5982/// C++20 [class.union]5.
5983static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5984 const LValue &LHS) {
5985 if (LHS.InvalidBase || LHS.Designator.Invalid)
5986 return false;
5987
5988 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5989 // C++ [class.union]p5:
5990 // define the set S(E) of subexpressions of E as follows:
5991 unsigned PathLength = LHS.Designator.Entries.size();
5992 for (const Expr *E = LHSExpr; E != nullptr;) {
5993 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5994 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5995 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5996 // Note that we can't implicitly start the lifetime of a reference,
5997 // so we don't need to proceed any further if we reach one.
5998 if (!FD || FD->getType()->isReferenceType())
5999 break;
6000
6001 // ... and also contains A.B if B names a union member ...
6002 if (FD->getParent()->isUnion()) {
6003 // ... of a non-class, non-array type, or of a class type with a
6004 // trivial default constructor that is not deleted, or an array of
6005 // such types.
6006 auto *RD =
6007 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6008 if (!RD || RD->hasTrivialDefaultConstructor())
6009 UnionPathLengths.push_back({PathLength - 1, FD});
6010 }
6011
6012 E = ME->getBase();
6013 --PathLength;
6014 assert(declaresSameEntity(FD,(static_cast <bool> (declaresSameEntity(FD, LHS.Designator
.Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void
(0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6016, __extension__ __PRETTY_FUNCTION__
))
6015 LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(FD, LHS.Designator
.Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void
(0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6016, __extension__ __PRETTY_FUNCTION__
))
6016 .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(FD, LHS.Designator
.Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void
(0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6016, __extension__ __PRETTY_FUNCTION__
))
;
6017
6018 // -- If E is of the form A[B] and is interpreted as a built-in array
6019 // subscripting operator, S(E) is [S(the array operand, if any)].
6020 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6021 // Step over an ArrayToPointerDecay implicit cast.
6022 auto *Base = ASE->getBase()->IgnoreImplicit();
6023 if (!Base->getType()->isArrayType())
6024 break;
6025
6026 E = Base;
6027 --PathLength;
6028
6029 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6030 // Step over a derived-to-base conversion.
6031 E = ICE->getSubExpr();
6032 if (ICE->getCastKind() == CK_NoOp)
6033 continue;
6034 if (ICE->getCastKind() != CK_DerivedToBase &&
6035 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6036 break;
6037 // Walk path backwards as we walk up from the base to the derived class.
6038 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6039 --PathLength;
6040 (void)Elt;
6041 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),(static_cast <bool> (declaresSameEntity(Elt->getType
()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength
] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail
("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6043, __extension__ __PRETTY_FUNCTION__
))
6042 LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(Elt->getType
()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength
] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail
("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6043, __extension__ __PRETTY_FUNCTION__
))
6043 .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(Elt->getType
()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength
] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail
("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "clang/lib/AST/ExprConstant.cpp", 6043, __extension__ __PRETTY_FUNCTION__
))
;
6044 }
6045
6046 // -- Otherwise, S(E) is empty.
6047 } else {
6048 break;
6049 }
6050 }
6051
6052 // Common case: no unions' lifetimes are started.
6053 if (UnionPathLengths.empty())
6054 return true;
6055
6056 // if modification of X [would access an inactive union member], an object
6057 // of the type of X is implicitly created
6058 CompleteObject Obj =
6059 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6060 if (!Obj)
6061 return false;
6062 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6063 llvm::reverse(UnionPathLengths)) {
6064 // Form a designator for the union object.
6065 SubobjectDesignator D = LHS.Designator;
6066 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6067
6068 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6069 ConstructionPhase::AfterBases;
6070 StartLifetimeOfUnionMemberHandler StartLifetime{
6071 Info, LHSExpr, LengthAndField.second, DuringInit};
6072 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6073 return false;
6074 }
6075
6076 return true;
6077}
6078
6079static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6080 CallRef Call, EvalInfo &Info,
6081 bool NonNull = false) {
6082 LValue LV;
6083 // Create the parameter slot and register its destruction. For a vararg
6084 // argument, create a temporary.
6085 // FIXME: For calling conventions that destroy parameters in the callee,
6086 // should we consider performing destruction when the function returns
6087 // instead?
6088 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6089 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6090 ScopeKind::Call, LV);
6091 if (!EvaluateInPlace(V, Info, LV, Arg))
6092 return false;
6093
6094 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6095 // undefined behavior, so is non-constant.
6096 if (NonNull && V.isLValue() && V.isNullPointer()) {
6097 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6098 return false;
6099 }
6100
6101 return true;
6102}
6103
6104/// Evaluate the arguments to a function call.
6105static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6106 EvalInfo &Info, const FunctionDecl *Callee,
6107 bool RightToLeft = false) {
6108 bool Success = true;
6109 llvm::SmallBitVector ForbiddenNullArgs;
6110 if (Callee->hasAttr<NonNullAttr>()) {
6111 ForbiddenNullArgs.resize(Args.size());
6112 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6113 if (!Attr->args_size()) {
6114 ForbiddenNullArgs.set();
6115 break;
6116 } else
6117 for (auto Idx : Attr->args()) {
6118 unsigned ASTIdx = Idx.getASTIndex();
6119 if (ASTIdx >= Args.size())
6120 continue;
6121 ForbiddenNullArgs[ASTIdx] = true;
6122 }
6123 }
6124 }
6125 for (unsigned I = 0; I < Args.size(); I++) {
6126 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6127 const ParmVarDecl *PVD =
6128 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6129 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6130 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6131 // If we're checking for a potential constant expression, evaluate all
6132 // initializers even if some of them fail.
6133 if (!Info.noteFailure())
6134 return false;
6135 Success = false;
6136 }
6137 }
6138 return Success;
6139}
6140
6141/// Perform a trivial copy from Param, which is the parameter of a copy or move
6142/// constructor or assignment operator.
6143static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6144 const Expr *E, APValue &Result,
6145 bool CopyObjectRepresentation) {
6146 // Find the reference argument.
6147 CallStackFrame *Frame = Info.CurrentCall;
6148 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6149 if (!RefValue) {
6150 Info.FFDiag(E);
6151 return false;
6152 }
6153
6154 // Copy out the contents of the RHS object.
6155 LValue RefLValue;
6156 RefLValue.setFrom(Info.Ctx, *RefValue);
6157 return handleLValueToRValueConversion(
6158 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6159 CopyObjectRepresentation);
6160}
6161
6162/// Evaluate a function call.
6163static bool HandleFunctionCall(SourceLocation CallLoc,
6164 const FunctionDecl *Callee, const LValue *This,
6165 ArrayRef<const Expr *> Args, CallRef Call,
6166 const Stmt *Body, EvalInfo &Info,
6167 APValue &Result, const LValue *ResultSlot) {
6168 if (!Info.CheckCallLimit(CallLoc))
6169 return false;
6170
6171 CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6172
6173 // For a trivial copy or move assignment, perform an APValue copy. This is
6174 // essential for unions, where the operations performed by the assignment
6175 // operator cannot be represented as statements.
6176 //
6177 // Skip this for non-union classes with no fields; in that case, the defaulted
6178 // copy/move does not actually read the object.
6179 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6180 if (MD && MD->isDefaulted() &&
6181 (MD->getParent()->isUnion() ||
6182 (MD->isTrivial() &&
6183 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6184 assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "clang/lib/AST/ExprConstant.cpp", 6185, __extension__ __PRETTY_FUNCTION__
))
6185 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "clang/lib/AST/ExprConstant.cpp", 6185, __extension__ __PRETTY_FUNCTION__
))
;
6186 APValue RHSValue;
6187 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6188 MD->getParent()->isUnion()))
6189 return false;
6190 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6191 RHSValue))
6192 return false;
6193 This->moveInto(Result);
6194 return true;
6195 } else if (MD && isLambdaCallOperator(MD)) {
6196 // We're in a lambda; determine the lambda capture field maps unless we're
6197 // just constexpr checking a lambda's call operator. constexpr checking is
6198 // done before the captures have been added to the closure object (unless
6199 // we're inferring constexpr-ness), so we don't have access to them in this
6200 // case. But since we don't need the captures to constexpr check, we can
6201 // just ignore them.
6202 if (!Info.checkingPotentialConstantExpression())
6203 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6204 Frame.LambdaThisCaptureField);
6205 }
6206
6207 StmtResult Ret = {Result, ResultSlot};
6208 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6209 if (ESR == ESR_Succeeded) {
6210 if (Callee->getReturnType()->isVoidType())
6211 return true;
6212 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6213 }
6214 return ESR == ESR_Returned;
6215}
6216
6217/// Evaluate a constructor call.
6218static bool HandleConstructorCall(const Expr *E, const LValue &This,
6219 CallRef Call,
6220 const CXXConstructorDecl *Definition,
6221 EvalInfo &Info, APValue &Result) {
6222 SourceLocation CallLoc = E->getExprLoc();
6223 if (!Info.CheckCallLimit(CallLoc))
6224 return false;
6225
6226 const CXXRecordDecl *RD = Definition->getParent();
6227 if (RD->getNumVBases()) {
6228 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6229 return false;
6230 }
6231
6232 EvalInfo::EvaluatingConstructorRAII EvalObj(
6233 Info,
6234 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6235 RD->getNumBases());
6236 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6237
6238 // FIXME: Creating an APValue just to hold a nonexistent return value is
6239 // wasteful.
6240 APValue RetVal;
6241 StmtResult Ret = {RetVal, nullptr};
6242
6243 // If it's a delegating constructor, delegate.
6244 if (Definition->isDelegatingConstructor()) {
6245 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6246 if ((*I)->getInit()->isValueDependent()) {
6247 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6248 return false;
6249 } else {
6250 FullExpressionRAII InitScope(Info);
6251 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6252 !InitScope.destroy())
6253 return false;
6254 }
6255 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6256 }
6257
6258 // For a trivial copy or move constructor, perform an APValue copy. This is
6259 // essential for unions (or classes with anonymous union members), where the
6260 // operations performed by the constructor cannot be represented by
6261 // ctor-initializers.
6262 //
6263 // Skip this for empty non-union classes; we should not perform an
6264 // lvalue-to-rvalue conversion on them because their copy constructor does not
6265 // actually read them.
6266 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6267 (Definition->getParent()->isUnion() ||
6268 (Definition->isTrivial() &&
6269 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6270 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6271 Definition->getParent()->isUnion());
6272 }
6273
6274 // Reserve space for the struct members.
6275 if (!Result.hasValue()) {
6276 if (!RD->isUnion())
6277 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6278 std::distance(RD->field_begin(), RD->field_end()));
6279 else
6280 // A union starts with no active member.
6281 Result = APValue((const FieldDecl*)nullptr);
6282 }
6283
6284 if (RD->isInvalidDecl()) return false;
6285 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6286
6287 // A scope for temporaries lifetime-extended by reference members.
6288 BlockScopeRAII LifetimeExtendedScope(Info);
6289
6290 bool Success = true;
6291 unsigned BasesSeen = 0;
6292#ifndef NDEBUG
6293 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6294#endif
6295 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6296 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6297 // We might be initializing the same field again if this is an indirect
6298 // field initialization.
6299 if (FieldIt == RD->field_end() ||
6300 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6301 assert(Indirect && "fields out of order?")(static_cast <bool> (Indirect && "fields out of order?"
) ? void (0) : __assert_fail ("Indirect && \"fields out of order?\""
, "clang/lib/AST/ExprConstant.cpp", 6301, __extension__ __PRETTY_FUNCTION__
))
;
6302 return;
6303 }
6304
6305 // Default-initialize any fields with no explicit initializer.
6306 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6307 assert(FieldIt != RD->field_end() && "missing field?")(static_cast <bool> (FieldIt != RD->field_end() &&
"missing field?") ? void (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\""
, "clang/lib/AST/ExprConstant.cpp", 6307, __extension__ __PRETTY_FUNCTION__
))
;
6308 if (!FieldIt->isUnnamedBitfield())
6309 Success &= getDefaultInitValue(
6310 FieldIt->getType(),
6311 Result.getStructField(FieldIt->getFieldIndex()));
6312 }
6313 ++FieldIt;
6314 };
6315 for (const auto *I : Definition->inits()) {
6316 LValue Subobject = This;
6317 LValue SubobjectParent = This;
6318 APValue *Value = &Result;
6319
6320 // Determine the subobject to initialize.
6321 FieldDecl *FD = nullptr;
6322 if (I->isBaseInitializer()) {
6323 QualType BaseType(I->getBaseClass(), 0);
6324#ifndef NDEBUG
6325 // Non-virtual base classes are initialized in the order in the class
6326 // definition. We have already checked for virtual base classes.
6327 assert(!BaseIt->isVirtual() && "virtual base for literal type")(static_cast <bool> (!BaseIt->isVirtual() &&
"virtual base for literal type") ? void (0) : __assert_fail (
"!BaseIt->isVirtual() && \"virtual base for literal type\""
, "clang/lib/AST/ExprConstant.cpp", 6327, __extension__ __PRETTY_FUNCTION__
))
;
6328 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType
(), BaseType) && "base class initializers not in expected order"
) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "clang/lib/AST/ExprConstant.cpp", 6329, __extension__ __PRETTY_FUNCTION__
))
6329 "base class initializers not in expected order")(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType
(), BaseType) && "base class initializers not in expected order"
) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "clang/lib/AST/ExprConstant.cpp", 6329, __extension__ __PRETTY_FUNCTION__
))
;
6330 ++BaseIt;
6331#endif
6332 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6333 BaseType->getAsCXXRecordDecl(), &Layout))
6334 return false;
6335 Value = &Result.getStructBase(BasesSeen++);
6336 } else if ((FD = I->getMember())) {
6337 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6338 return false;
6339 if (RD->isUnion()) {
6340 Result = APValue(FD);
6341 Value = &Result.getUnionValue();
6342 } else {
6343 SkipToField(FD, false);
6344 Value = &Result.getStructField(FD->getFieldIndex());
6345 }
6346 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6347 // Walk the indirect field decl's chain to find the object to initialize,
6348 // and make sure we've initialized every step along it.
6349 auto IndirectFieldChain = IFD->chain();
6350 for (auto *C : IndirectFieldChain) {
6351 FD = cast<FieldDecl>(C);
6352 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6353 // Switch the union field if it differs. This happens if we had
6354 // preceding zero-initialization, and we're now initializing a union
6355 // subobject other than the first.
6356 // FIXME: In this case, the values of the other subobjects are
6357 // specified, since zero-initialization sets all padding bits to zero.
6358 if (!Value->hasValue() ||
6359 (Value->isUnion() && Value->getUnionField() != FD)) {
6360 if (CD->isUnion())
6361 *Value = APValue(FD);
6362 else
6363 // FIXME: This immediately starts the lifetime of all members of
6364 // an anonymous struct. It would be preferable to strictly start
6365 // member lifetime in initialization order.
6366 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6367 }
6368 // Store Subobject as its parent before updating it for the last element
6369 // in the chain.
6370 if (C == IndirectFieldChain.back())
6371 SubobjectParent = Subobject;
6372 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6373 return false;
6374 if (CD->isUnion())
6375 Value = &Value->getUnionValue();
6376 else {
6377 if (C == IndirectFieldChain.front() && !RD->isUnion())
6378 SkipToField(FD, true);
6379 Value = &Value->getStructField(FD->getFieldIndex());
6380 }
6381 }
6382 } else {
6383 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "clang/lib/AST/ExprConstant.cpp", 6383)
;
6384 }
6385
6386 // Need to override This for implicit field initializers as in this case
6387 // This refers to innermost anonymous struct/union containing initializer,
6388 // not to currently constructed class.
6389 const Expr *Init = I->getInit();
6390 if (Init->isValueDependent()) {
6391 if (!EvaluateDependentExpr(Init, Info))
6392 return false;
6393 } else {
6394 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6395 isa<CXXDefaultInitExpr>(Init));
6396 FullExpressionRAII InitScope(Info);
6397 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6398 (FD && FD->isBitField() &&
6399 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6400 // If we're checking for a potential constant expression, evaluate all
6401 // initializers even if some of them fail.
6402 if (!Info.noteFailure())
6403 return false;
6404 Success = false;
6405 }
6406 }
6407
6408 // This is the point at which the dynamic type of the object becomes this
6409 // class type.
6410 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6411 EvalObj.finishedConstructingBases();
6412 }
6413
6414 // Default-initialize any remaining fields.
6415 if (!RD->isUnion()) {
6416 for (; FieldIt != RD->field_end(); ++FieldIt) {
6417 if (!FieldIt->isUnnamedBitfield())
6418 Success &= getDefaultInitValue(
6419 FieldIt->getType(),
6420 Result.getStructField(FieldIt->getFieldIndex()));
6421 }
6422 }
6423
6424 EvalObj.finishedConstructingFields();
6425
6426 return Success &&
6427 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6428 LifetimeExtendedScope.destroy();
6429}
6430
6431static bool HandleConstructorCall(const Expr *E, const LValue &This,
6432 ArrayRef<const Expr*> Args,
6433 const CXXConstructorDecl *Definition,
6434 EvalInfo &Info, APValue &Result) {
6435 CallScopeRAII CallScope(Info);
6436 CallRef Call = Info.CurrentCall->createCall(Definition);
6437 if (!EvaluateArgs(Args, Call, Info, Definition))
6438 return false;
6439
6440 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6441 CallScope.destroy();
6442}
6443
6444static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6445 const LValue &This, APValue &Value,
6446 QualType T) {
6447 // Objects can only be destroyed while they're within their lifetimes.
6448 // FIXME: We have no representation for whether an object of type nullptr_t
6449 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6450 // as indeterminate instead?
6451 if (Value.isAbsent() && !T->isNullPtrType()) {
6452 APValue Printable;
6453 This.moveInto(Printable);
6454 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6455 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6456 return false;
6457 }
6458
6459 // Invent an expression for location purposes.
6460 // FIXME: We shouldn't need to do this.
6461 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6462
6463 // For arrays, destroy elements right-to-left.
6464 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6465 uint64_t Size = CAT->getSize().getZExtValue();
6466 QualType ElemT = CAT->getElementType();
6467
6468 LValue ElemLV = This;
6469 ElemLV.addArray(Info, &LocE, CAT);
6470 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6471 return false;
6472
6473 // Ensure that we have actual array elements available to destroy; the
6474 // destructors might mutate the value, so we can't run them on the array
6475 // filler.
6476 if (Size && Size > Value.getArrayInitializedElts())
6477 expandArray(Value, Value.getArraySize() - 1);
6478
6479 for (; Size != 0; --Size) {
6480 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6481 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6482 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6483 return false;
6484 }
6485
6486 // End the lifetime of this array now.
6487 Value = APValue();
6488 return true;
6489 }
6490
6491 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6492 if (!RD) {
6493 if (T.isDestructedType()) {
6494 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6495 return false;
6496 }
6497
6498 Value = APValue();
6499 return true;
6500 }
6501
6502 if (RD->getNumVBases()) {
6503 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6504 return false;
6505 }
6506
6507 const CXXDestructorDecl *DD = RD->getDestructor();
6508 if (!DD && !RD->hasTrivialDestructor()) {
6509 Info.FFDiag(CallLoc);
6510 return false;
6511 }
6512
6513 if (!DD || DD->isTrivial() ||
6514 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6515 // A trivial destructor just ends the lifetime of the object. Check for
6516 // this case before checking for a body, because we might not bother
6517 // building a body for a trivial destructor. Note that it doesn't matter
6518 // whether the destructor is constexpr in this case; all trivial
6519 // destructors are constexpr.
6520 //
6521 // If an anonymous union would be destroyed, some enclosing destructor must
6522 // have been explicitly defined, and the anonymous union destruction should
6523 // have no effect.
6524 Value = APValue();
6525 return true;
6526 }
6527
6528 if (!Info.CheckCallLimit(CallLoc))
6529 return false;
6530
6531 const FunctionDecl *Definition = nullptr;
6532 const Stmt *Body = DD->getBody(Definition);
6533
6534 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6535 return false;
6536
6537 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6538
6539 // We're now in the period of destruction of this object.
6540 unsigned BasesLeft = RD->getNumBases();
6541 EvalInfo::EvaluatingDestructorRAII EvalObj(
6542 Info,
6543 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6544 if (!EvalObj.DidInsert) {
6545 // C++2a [class.dtor]p19:
6546 // the behavior is undefined if the destructor is invoked for an object
6547 // whose lifetime has ended
6548 // (Note that formally the lifetime ends when the period of destruction
6549 // begins, even though certain uses of the object remain valid until the
6550 // period of destruction ends.)
6551 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6552 return false;
6553 }
6554
6555 // FIXME: Creating an APValue just to hold a nonexistent return value is
6556 // wasteful.
6557 APValue RetVal;
6558 StmtResult Ret = {RetVal, nullptr};
6559 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6560 return false;
6561
6562 // A union destructor does not implicitly destroy its members.
6563 if (RD->isUnion())
6564 return true;
6565
6566 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6567
6568 // We don't have a good way to iterate fields in reverse, so collect all the
6569 // fields first and then walk them backwards.
6570 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6571 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6572 if (FD->isUnnamedBitfield())
6573 continue;
6574
6575 LValue Subobject = This;
6576 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6577 return false;
6578
6579 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6580 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6581 FD->getType()))
6582 return false;
6583 }
6584
6585 if (BasesLeft != 0)
6586 EvalObj.startedDestroyingBases();
6587
6588 // Destroy base classes in reverse order.
6589 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6590 --BasesLeft;
6591
6592 QualType BaseType = Base.getType();
6593 LValue Subobject = This;
6594 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6595 BaseType->getAsCXXRecordDecl(), &Layout))
6596 return false;
6597
6598 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6599 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6600 BaseType))
6601 return false;
6602 }
6603 assert(BasesLeft == 0 && "NumBases was wrong?")(static_cast <bool> (BasesLeft == 0 && "NumBases was wrong?"
) ? void (0) : __assert_fail ("BasesLeft == 0 && \"NumBases was wrong?\""
, "clang/lib/AST/ExprConstant.cpp", 6603, __extension__ __PRETTY_FUNCTION__
))
;
6604
6605 // The period of destruction ends now. The object is gone.
6606 Value = APValue();
6607 return true;
6608}
6609
6610namespace {
6611struct DestroyObjectHandler {
6612 EvalInfo &Info;
6613 const Expr *E;
6614 const LValue &This;
6615 const AccessKinds AccessKind;
6616
6617 typedef bool result_type;
6618 bool failed() { return false; }
6619 bool found(APValue &Subobj, QualType SubobjType) {
6620 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6621 SubobjType);
6622 }
6623 bool found(APSInt &Value, QualType SubobjType) {
6624 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6625 return false;
6626 }
6627 bool found(APFloat &Value, QualType SubobjType) {
6628 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6629 return false;
6630 }
6631};
6632}
6633
6634/// Perform a destructor or pseudo-destructor call on the given object, which
6635/// might in general not be a complete object.
6636static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6637 const LValue &This, QualType ThisType) {
6638 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6639 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6640 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6641}
6642
6643/// Destroy and end the lifetime of the given complete object.
6644static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6645 APValue::LValueBase LVBase, APValue &Value,
6646 QualType T) {
6647 // If we've had an unmodeled side-effect, we can't rely on mutable state
6648 // (such as the object we're about to destroy) being correct.
6649 if (Info.EvalStatus.HasSideEffects)
6650 return false;
6651
6652 LValue LV;
6653 LV.set({LVBase});
6654 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6655}
6656
6657/// Perform a call to 'perator new' or to `__builtin_operator_new'.
6658static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6659 LValue &Result) {
6660 if (Info.checkingPotentialConstantExpression() ||
6661 Info.SpeculativeEvaluationDepth)
6662 return false;
6663
6664 // This is permitted only within a call to std::allocator<T>::allocate.
6665 auto Caller = Info.getStdAllocatorCaller("allocate");
6666 if (!Caller) {
6667 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6668 ? diag::note_constexpr_new_untyped
6669 : diag::note_constexpr_new);
6670 return false;
6671 }
6672
6673 QualType ElemType = Caller.ElemType;
6674 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6675 Info.FFDiag(E->getExprLoc(),
6676 diag::note_constexpr_new_not_complete_object_type)
6677 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6678 return false;
6679 }
6680
6681 APSInt ByteSize;
6682 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6683 return false;
6684 bool IsNothrow = false;
6685 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6686 EvaluateIgnoredValue(Info, E->getArg(I));
6687 IsNothrow |= E->getType()->isNothrowT();
6688 }
6689
6690 CharUnits ElemSize;
6691 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6692 return false;
6693 APInt Size, Remainder;
6694 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6695 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6696 if (Remainder != 0) {
6697 // This likely indicates a bug in the implementation of 'std::allocator'.
6698 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6699 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6700 return false;
6701 }
6702
6703 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6704 if (IsNothrow) {
6705 Result.setNull(Info.Ctx, E->getType());
6706 return true;
6707 }
6708
6709 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6710 return false;
6711 }
6712
6713 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6714 ArrayType::Normal, 0);
6715 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6716 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6717 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6718 return true;
6719}
6720
6721static bool hasVirtualDestructor(QualType T) {
6722 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6723 if (CXXDestructorDecl *DD = RD->getDestructor())
6724 return DD->isVirtual();
6725 return false;
6726}
6727
6728static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6729 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6730 if (CXXDestructorDecl *DD = RD->getDestructor())
6731 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6732 return nullptr;
6733}
6734
6735/// Check that the given object is a suitable pointer to a heap allocation that
6736/// still exists and is of the right kind for the purpose of a deletion.
6737///
6738/// On success, returns the heap allocation to deallocate. On failure, produces
6739/// a diagnostic and returns std::nullopt.
6740static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6741 const LValue &Pointer,
6742 DynAlloc::Kind DeallocKind) {
6743 auto PointerAsString = [&] {
6744 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6745 };
6746
6747 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6748 if (!DA) {
6749 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6750 << PointerAsString();
6751 if (Pointer.Base)
6752 NoteLValueLocation(Info, Pointer.Base);
6753 return std::nullopt;
6754 }
6755
6756 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6757 if (!Alloc) {
6758 Info.FFDiag(E, diag::note_constexpr_double_delete);
6759 return std::nullopt;
6760 }
6761
6762 QualType AllocType = Pointer.Base.getDynamicAllocType();
6763 if (DeallocKind != (*Alloc)->getKind()) {
6764 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6765 << DeallocKind << (*Alloc)->getKind() << AllocType;
6766 NoteLValueLocation(Info, Pointer.Base);
6767 return std::nullopt;
6768 }
6769
6770 bool Subobject = false;
6771 if (DeallocKind == DynAlloc::New) {
6772 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6773 Pointer.Designator.isOnePastTheEnd();
6774 } else {
6775 Subobject = Pointer.Designator.Entries.size() != 1 ||
6776 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6777 }
6778 if (Subobject) {
6779 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6780 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6781 return std::nullopt;
6782 }
6783
6784 return Alloc;
6785}
6786
6787// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6788bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6789 if (Info.checkingPotentialConstantExpression() ||
6790 Info.SpeculativeEvaluationDepth)
6791 return false;
6792
6793 // This is permitted only within a call to std::allocator<T>::deallocate.
6794 if (!Info.getStdAllocatorCaller("deallocate")) {
6795 Info.FFDiag(E->getExprLoc());
6796 return true;
6797 }
6798
6799 LValue Pointer;
6800 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6801 return false;
6802 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6803 EvaluateIgnoredValue(Info, E->getArg(I));
6804
6805 if (Pointer.Designator.Invalid)
6806 return false;
6807
6808 // Deleting a null pointer would have no effect, but it's not permitted by
6809 // std::allocator<T>::deallocate's contract.
6810 if (Pointer.isNullPointer()) {
6811 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6812 return true;
6813 }
6814
6815 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6816 return false;
6817
6818 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6819 return true;
6820}
6821
6822//===----------------------------------------------------------------------===//
6823// Generic Evaluation
6824//===----------------------------------------------------------------------===//
6825namespace {
6826
6827class BitCastBuffer {
6828 // FIXME: We're going to need bit-level granularity when we support
6829 // bit-fields.
6830 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6831 // we don't support a host or target where that is the case. Still, we should
6832 // use a more generic type in case we ever do.
6833 SmallVector<std::optional<unsigned char>, 32> Bytes;
6834
6835 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6836 "Need at least 8 bit unsigned char");
6837
6838 bool TargetIsLittleEndian;
6839
6840public:
6841 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6842 : Bytes(Width.getQuantity()),
6843 TargetIsLittleEndian(TargetIsLittleEndian) {}
6844
6845 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6846 SmallVectorImpl<unsigned char> &Output) const {
6847 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6848 // If a byte of an integer is uninitialized, then the whole integer is
6849 // uninitialized.
6850 if (!Bytes[I.getQuantity()])
6851 return false;
6852 Output.push_back(*Bytes[I.getQuantity()]);
6853 }
6854 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6855 std::reverse(Output.begin(), Output.end());
6856 return true;
6857 }
6858
6859 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6860 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6861 std::reverse(Input.begin(), Input.end());
6862
6863 size_t Index = 0;
6864 for (unsigned char Byte : Input) {
6865 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")(static_cast <bool> (!Bytes[Offset.getQuantity() + Index
] && "overwriting a byte?") ? void (0) : __assert_fail
("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\""
, "clang/lib/AST/ExprConstant.cpp", 6865, __extension__ __PRETTY_FUNCTION__
))
;
6866 Bytes[Offset.getQuantity() + Index] = Byte;
6867 ++Index;
6868 }
6869 }
6870
6871 size_t size() { return Bytes.size(); }
6872};
6873
6874/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6875/// target would represent the value at runtime.
6876class APValueToBufferConverter {
6877 EvalInfo &Info;
6878 BitCastBuffer Buffer;
6879 const CastExpr *BCE;
6880
6881 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6882 const CastExpr *BCE)
6883 : Info(Info),
6884 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6885 BCE(BCE) {}
6886
6887 bool visit(const APValue &Val, QualType Ty) {
6888 return visit(Val, Ty, CharUnits::fromQuantity(0));
6889 }
6890
6891 // Write out Val with type Ty into Buffer starting at Offset.
6892 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6893 assert((size_t)Offset.getQuantity() <= Buffer.size())(static_cast <bool> ((size_t)Offset.getQuantity() <=
Buffer.size()) ? void (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()"
, "clang/lib/AST/ExprConstant.cpp", 6893, __extension__ __PRETTY_FUNCTION__
))
;
6894
6895 // As a special case, nullptr_t has an indeterminate value.
6896 if (Ty->isNullPtrType())
6897 return true;
6898
6899 // Dig through Src to find the byte at SrcOffset.
6900 switch (Val.getKind()) {
6901 case APValue::Indeterminate:
6902 case APValue::None:
6903 return true;
6904
6905 case APValue::Int:
6906 return visitInt(Val.getInt(), Ty, Offset);
6907 case APValue::Float:
6908 return visitFloat(Val.getFloat(), Ty, Offset);
6909 case APValue::Array:
6910 return visitArray(Val, Ty, Offset);
6911 case APValue::Struct:
6912 return visitRecord(Val, Ty, Offset);
6913
6914 case APValue::ComplexInt:
6915 case APValue::ComplexFloat:
6916 case APValue::Vector:
6917 case APValue::FixedPoint:
6918 // FIXME: We should support these.
6919
6920 case APValue::Union:
6921 case APValue::MemberPointer:
6922 case APValue::AddrLabelDiff: {
6923 Info.FFDiag(BCE->getBeginLoc(),
6924 diag::note_constexpr_bit_cast_unsupported_type)
6925 << Ty;
6926 return false;
6927 }
6928
6929 case APValue::LValue:
6930 llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?"
, "clang/lib/AST/ExprConstant.cpp", 6930)
;
6931 }
6932 llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind"
, "clang/lib/AST/ExprConstant.cpp", 6932)
;
6933 }
6934
6935 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6936 const RecordDecl *RD = Ty->getAsRecordDecl();
6937 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6938
6939 // Visit the base classes.
6940 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6941 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6942 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6943 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6944
6945 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6946 Layout.getBaseClassOffset(BaseDecl) + Offset))
6947 return false;
6948 }
6949 }
6950
6951 // Visit the fields.
6952 unsigned FieldIdx = 0;
6953 for (FieldDecl *FD : RD->fields()) {
6954 if (FD->isBitField()) {
6955 Info.FFDiag(BCE->getBeginLoc(),
6956 diag::note_constexpr_bit_cast_unsupported_bitfield);
6957 return false;
6958 }
6959
6960 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6961
6962 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth
() == 0 && "only bit-fields can have sub-char alignment"
) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\""
, "clang/lib/AST/ExprConstant.cpp", 6963, __extension__ __PRETTY_FUNCTION__
))
6963 "only bit-fields can have sub-char alignment")(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth
() == 0 && "only bit-fields can have sub-char alignment"
) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\""
, "clang/lib/AST/ExprConstant.cpp", 6963, __extension__ __PRETTY_FUNCTION__
))
;
6964 CharUnits FieldOffset =
6965 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6966 QualType FieldTy = FD->getType();
6967 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6968 return false;
6969 ++FieldIdx;
6970 }
6971
6972 return true;
6973 }
6974
6975 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6976 const auto *CAT =
6977 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6978 if (!CAT)
6979 return false;
6980
6981 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6982 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6983 unsigned ArraySize = Val.getArraySize();
6984 // First, initialize the initialized elements.
6985 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6986 const APValue &SubObj = Val.getArrayInitializedElt(I);
6987 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6988 return false;
6989 }
6990
6991 // Next, initialize the rest of the array using the filler.
6992 if (Val.hasArrayFiller()) {
6993 const APValue &Filler = Val.getArrayFiller();
6994 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6995 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6996 return false;
6997 }
6998 }
6999
7000 return true;
7001 }
7002
7003 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7004 APSInt AdjustedVal = Val;
7005 unsigned Width = AdjustedVal.getBitWidth();
7006 if (Ty->isBooleanType()) {
7007 Width = Info.Ctx.getTypeSize(Ty);
7008 AdjustedVal = AdjustedVal.extend(Width);
7009 }
7010
7011 SmallVector<unsigned char, 8> Bytes(Width / 8);
7012 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7013 Buffer.writeObject(Offset, Bytes);
7014 return true;
7015 }
7016
7017 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7018 APSInt AsInt(Val.bitcastToAPInt());
7019 return visitInt(AsInt, Ty, Offset);
7020 }
7021
7022public:
7023 static std::optional<BitCastBuffer>
7024 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7025 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7026 APValueToBufferConverter Converter(Info, DstSize, BCE);
7027 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7028 return std::nullopt;
7029 return Converter.Buffer;
7030 }
7031};
7032
7033/// Write an BitCastBuffer into an APValue.
7034class BufferToAPValueConverter {
7035 EvalInfo &Info;
7036 const BitCastBuffer &Buffer;
7037 const CastExpr *BCE;
7038
7039 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7040 const CastExpr *BCE)
7041 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7042
7043 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7044 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7045 // Ideally this will be unreachable.
7046 std::nullopt_t unsupportedType(QualType Ty) {
7047 Info.FFDiag(BCE->getBeginLoc(),
7048 diag::note_constexpr_bit_cast_unsupported_type)
7049 << Ty;
7050 return std::nullopt;
7051 }
7052
7053 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7054 Info.FFDiag(BCE->getBeginLoc(),
7055 diag::note_constexpr_bit_cast_unrepresentable_value)
7056 << Ty << toString(Val, /*Radix=*/10);
7057 return std::nullopt;
7058 }
7059
7060 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7061 const EnumType *EnumSugar = nullptr) {
7062 if (T->isNullPtrType()) {
7063 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7064 return APValue((Expr *)nullptr,
7065 /*Offset=*/CharUnits::fromQuantity(NullValue),
7066 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7067 }
7068
7069 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7070
7071 // Work around floating point types that contain unused padding bytes. This
7072 // is really just `long double` on x86, which is the only fundamental type
7073 // with padding bytes.
7074 if (T->isRealFloatingType()) {
7075 const llvm::fltSemantics &Semantics =
7076 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7077 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7078 assert(NumBits % 8 == 0)(static_cast <bool> (NumBits % 8 == 0) ? void (0) : __assert_fail
("NumBits % 8 == 0", "clang/lib/AST/ExprConstant.cpp", 7078,
__extension__ __PRETTY_FUNCTION__))
;
7079 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7080 if (NumBytes != SizeOf)
7081 SizeOf = NumBytes;
7082 }
7083
7084 SmallVector<uint8_t, 8> Bytes;
7085 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7086 // If this is std::byte or unsigned char, then its okay to store an
7087 // indeterminate value.
7088 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7089 bool IsUChar =
7090 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7091 T->isSpecificBuiltinType(BuiltinType::Char_U));
7092 if (!IsStdByte && !IsUChar) {
7093 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7094 Info.FFDiag(BCE->getExprLoc(),
7095 diag::note_constexpr_bit_cast_indet_dest)
7096 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7097 return std::nullopt;
7098 }
7099
7100 return APValue::IndeterminateValue();
7101 }
7102
7103 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7104 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7105
7106 if (T->isIntegralOrEnumerationType()) {
7107 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7108
7109 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7110 if (IntWidth != Val.getBitWidth()) {
7111 APSInt Truncated = Val.trunc(IntWidth);
7112 if (Truncated.extend(Val.getBitWidth()) != Val)
7113 return unrepresentableValue(QualType(T, 0), Val);
7114 Val = Truncated;
7115 }
7116
7117 return APValue(Val);
7118 }
7119
7120 if (T->isRealFloatingType()) {
7121 const llvm::fltSemantics &Semantics =
7122 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7123 return APValue(APFloat(Semantics, Val));
7124 }
7125
7126 return unsupportedType(QualType(T, 0));
7127 }
7128
7129 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7130 const RecordDecl *RD = RTy->getAsRecordDecl();
7131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7132
7133 unsigned NumBases = 0;
7134 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7135 NumBases = CXXRD->getNumBases();
7136
7137 APValue ResultVal(APValue::UninitStruct(), NumBases,
7138 std::distance(RD->field_begin(), RD->field_end()));
7139
7140 // Visit the base classes.
7141 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7142 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7143 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7144 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7145 if (BaseDecl->isEmpty() ||
7146 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7147 continue;
7148
7149 std::optional<APValue> SubObj = visitType(
7150 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7151 if (!SubObj)
7152 return std::nullopt;
7153 ResultVal.getStructBase(I) = *SubObj;
7154 }
7155 }
7156
7157 // Visit the fields.
7158 unsigned FieldIdx = 0;
7159 for (FieldDecl *FD : RD->fields()) {
7160 // FIXME: We don't currently support bit-fields. A lot of the logic for
7161 // this is in CodeGen, so we need to factor it around.
7162 if (FD->isBitField()) {
7163 Info.FFDiag(BCE->getBeginLoc(),
7164 diag::note_constexpr_bit_cast_unsupported_bitfield);
7165 return std::nullopt;
7166 }
7167
7168 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7169 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth
() == 0) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0"
, "clang/lib/AST/ExprConstant.cpp", 7169, __extension__ __PRETTY_FUNCTION__
))
;
7170
7171 CharUnits FieldOffset =
7172 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7173 Offset;
7174 QualType FieldTy = FD->getType();
7175 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7176 if (!SubObj)
7177 return std::nullopt;
7178 ResultVal.getStructField(FieldIdx) = *SubObj;
7179 ++FieldIdx;
7180 }
7181
7182 return ResultVal;
7183 }
7184
7185 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7186 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7187 assert(!RepresentationType.isNull() &&(static_cast <bool> (!RepresentationType.isNull() &&
"enum forward decl should be caught by Sema") ? void (0) : __assert_fail
("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\""
, "clang/lib/AST/ExprConstant.cpp", 7188, __extension__ __PRETTY_FUNCTION__
))
7188 "enum forward decl should be caught by Sema")(static_cast <bool> (!RepresentationType.isNull() &&
"enum forward decl should be caught by Sema") ? void (0) : __assert_fail
("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\""
, "clang/lib/AST/ExprConstant.cpp", 7188, __extension__ __PRETTY_FUNCTION__
))
;
7189 const auto *AsBuiltin =
7190 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7191 // Recurse into the underlying type. Treat std::byte transparently as
7192 // unsigned char.
7193 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7194 }
7195
7196 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7197 size_t Size = Ty->getSize().getLimitedValue();
7198 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7199
7200 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7201 for (size_t I = 0; I != Size; ++I) {
7202 std::optional<APValue> ElementValue =
7203 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7204 if (!ElementValue)
7205 return std::nullopt;
7206 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7207 }
7208
7209 return ArrayValue;
7210 }
7211
7212 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7213 return unsupportedType(QualType(Ty, 0));
7214 }
7215
7216 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7217 QualType Can = Ty.getCanonicalType();
7218
7219 switch (Can->getTypeClass()) {
7220#define TYPE(Class, Base) \
7221 case Type::Class: \
7222 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7223#define ABSTRACT_TYPE(Class, Base)
7224#define NON_CANONICAL_TYPE(Class, Base) \
7225 case Type::Class: \
7226 llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!"
, "clang/lib/AST/ExprConstant.cpp", 7226)
;
7227#define DEPENDENT_TYPE(Class, Base) \
7228 case Type::Class: \
7229 llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!"
, "clang/lib/AST/ExprConstant.cpp", 7230)
7230 "dependent types aren't supported in the constant evaluator!")::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!"
, "clang/lib/AST/ExprConstant.cpp", 7230)
;
7231#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "clang/lib/AST/ExprConstant.cpp", 7231);
\
7232 case Type::Class: \
7233 llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "clang/lib/AST/ExprConstant.cpp", 7233)
;
7234#include "clang/AST/TypeNodes.inc"
7235 }
7236 llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass"
, "clang/lib/AST/ExprConstant.cpp", 7236)
;
7237 }
7238
7239public:
7240 // Pull out a full value of type DstType.
7241 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7242 const CastExpr *BCE) {
7243 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7244 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7245 }
7246};
7247
7248static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7249 QualType Ty, EvalInfo *Info,
7250 const ASTContext &Ctx,
7251 bool CheckingDest) {
7252 Ty = Ty.getCanonicalType();
7253
7254 auto diag = [&](int Reason) {
7255 if (Info)
7256 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7257 << CheckingDest << (Reason == 4) << Reason;
7258 return false;
7259 };
7260 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7261 if (Info)
7262 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7263 << NoteTy << Construct << Ty;
7264 return false;
7265 };
7266
7267 if (Ty->isUnionType())
7268 return diag(0);
7269 if (Ty->isPointerType())
7270 return diag(1);
7271 if (Ty->isMemberPointerType())
7272 return diag(2);
7273 if (Ty.isVolatileQualified())
7274 return diag(3);
7275
7276 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7277 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7278 for (CXXBaseSpecifier &BS : CXXRD->bases())
7279 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7280 CheckingDest))
7281 return note(1, BS.getType(), BS.getBeginLoc());
7282 }
7283 for (FieldDecl *FD : Record->fields()) {
7284 if (FD->getType()->isReferenceType())
7285 return diag(4);
7286 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7287 CheckingDest))
7288 return note(0, FD->getType(), FD->getBeginLoc());
7289 }
7290 }
7291
7292 if (Ty->isArrayType() &&
7293 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7294 Info, Ctx, CheckingDest))
7295 return false;
7296
7297 return true;
7298}
7299
7300static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7301 const ASTContext &Ctx,
7302 const CastExpr *BCE) {
7303 bool DestOK = checkBitCastConstexprEligibilityType(
7304 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7305 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7306 BCE->getBeginLoc(),
7307 BCE->getSubExpr()->getType(), Info, Ctx, false);
7308 return SourceOK;
7309}
7310
7311static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7312 APValue &SourceValue,
7313 const CastExpr *BCE) {
7314 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo
().getCharWidth() == 8 && "no host or target supports non 8-bit chars"
) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\""
, "clang/lib/AST/ExprConstant.cpp", 7315, __extension__ __PRETTY_FUNCTION__
))
7315 "no host or target supports non 8-bit chars")(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo
().getCharWidth() == 8 && "no host or target supports non 8-bit chars"
) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\""
, "clang/lib/AST/ExprConstant.cpp", 7315, __extension__ __PRETTY_FUNCTION__
))
;
7316 assert(SourceValue.isLValue() &&(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!"
) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\""
, "clang/lib/AST/ExprConstant.cpp", 7317, __extension__ __PRETTY_FUNCTION__
))
7317 "LValueToRValueBitcast requires an lvalue operand!")(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!"
) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\""
, "clang/lib/AST/ExprConstant.cpp", 7317, __extension__ __PRETTY_FUNCTION__
))
;
7318
7319 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7320 return false;
7321
7322 LValue SourceLValue;
7323 APValue SourceRValue;
7324 SourceLValue.setFrom(Info.Ctx, SourceValue);
7325 if (!handleLValueToRValueConversion(
7326 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7327 SourceRValue, /*WantObjectRepresentation=*/true))
7328 return false;
7329
7330 // Read out SourceValue into a char buffer.
7331 std::optional<BitCastBuffer> Buffer =
7332 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7333 if (!Buffer)
7334 return false;
7335
7336 // Write out the buffer into a new APValue.
7337 std::optional<APValue> MaybeDestValue =
7338 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7339 if (!MaybeDestValue)
7340 return false;
7341
7342 DestValue = std::move(*MaybeDestValue);
7343 return true;
7344}
7345
7346template <class Derived>
7347class ExprEvaluatorBase
7348 : public ConstStmtVisitor<Derived, bool> {
7349private:
7350 Derived &getDerived() { return static_cast<Derived&>(*this); }
7351 bool DerivedSuccess(const APValue &V, const Expr *E) {
7352 return getDerived().Success(V, E);
7353 }
7354 bool DerivedZeroInitialization(const Expr *E) {
7355 return getDerived().ZeroInitialization(E);
7356 }
7357
7358 // Check whether a conditional operator with a non-constant condition is a
7359 // potential constant expression. If neither arm is a potential constant
7360 // expression, then the conditional operator is not either.
7361 template<typename ConditionalOperator>
7362 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7363 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "clang/lib/AST/ExprConstant.cpp", 7363, __extension__ __PRETTY_FUNCTION__
))
;
7364
7365 // Speculatively evaluate both arms.
7366 SmallVector<PartialDiagnosticAt, 8> Diag;
7367 {
7368 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7369 StmtVisitorTy::Visit(E->getFalseExpr());
7370 if (Diag.empty())
7371 return;
7372 }
7373
7374 {
7375 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7376 Diag.clear();
7377 StmtVisitorTy::Visit(E->getTrueExpr());
7378 if (Diag.empty())
7379 return;
7380 }
7381
7382 Error(E, diag::note_constexpr_conditional_never_const);
7383 }
7384
7385
7386 template<typename ConditionalOperator>
7387 bool HandleConditionalOperator(const ConditionalOperator *E) {
7388 bool BoolResult;
7389 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7390 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7391 CheckPotentialConstantConditional(E);
7392 return false;
7393 }
7394 if (Info.noteFailure()) {
7395 StmtVisitorTy::Visit(E->getTrueExpr());
7396 StmtVisitorTy::Visit(E->getFalseExpr());
7397 }
7398 return false;
7399 }
7400
7401 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7402 return StmtVisitorTy::Visit(EvalExpr);
7403 }
7404
7405protected:
7406 EvalInfo &Info;
7407 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7408 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7409
7410 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7411 return Info.CCEDiag(E, D);
7412 }
7413
7414 bool ZeroInitialization(const Expr *E) { return Error(E); }
7415
7416 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7417 unsigned BuiltinOp = E->getBuiltinCallee();
7418 return BuiltinOp != 0 &&
7419 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7420 }
7421
7422public:
7423 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7424
7425 EvalInfo &getEvalInfo() { return Info; }
7426
7427 /// Report an evaluation error. This should only be called when an error is
7428 /// first discovered. When propagating an error, just return false.
7429 bool Error(const Expr *E, diag::kind D) {
7430 Info.FFDiag(E, D);
7431 return false;
7432 }
7433 bool Error(const Expr *E) {
7434 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7435 }
7436
7437 bool VisitStmt(const Stmt *) {
7438 llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts"
, "clang/lib/AST/ExprConstant.cpp", 7438)
;
7439 }
7440 bool VisitExpr(const Expr *E) {
7441 return Error(E);
7442 }
7443
7444 bool VisitConstantExpr(const ConstantExpr *E) {
7445 if (E->hasAPValueResult())
7446 return DerivedSuccess(E->getAPValueResult(), E);
7447
7448 return StmtVisitorTy::Visit(E->getSubExpr());
7449 }
7450
7451 bool VisitParenExpr(const ParenExpr *E)
7452 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7453 bool VisitUnaryExtension(const UnaryOperator *E)
7454 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7455 bool VisitUnaryPlus(const UnaryOperator *E)
7456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7457 bool VisitChooseExpr(const ChooseExpr *E)
7458 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7459 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7460 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7461 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7462 { return StmtVisitorTy::Visit(E->getReplacement()); }
7463 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7464 TempVersionRAII RAII(*Info.CurrentCall);
7465 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7466 return StmtVisitorTy::Visit(E->getExpr());
7467 }
7468 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7469 TempVersionRAII RAII(*Info.CurrentCall);
7470 // The initializer may not have been parsed yet, or might be erroneous.
7471 if (!E->getExpr())
7472 return Error(E);
7473 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7474 return StmtVisitorTy::Visit(E->getExpr());
7475 }
7476
7477 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7478 FullExpressionRAII Scope(Info);
7479 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7480 }
7481
7482 // Temporaries are registered when created, so we don't care about
7483 // CXXBindTemporaryExpr.
7484 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7485 return StmtVisitorTy::Visit(E->getSubExpr());
7486 }
7487
7488 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7489 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7490 return static_cast<Derived*>(this)->VisitCastExpr(E);
7491 }
7492 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7493 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7494 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7495 return static_cast<Derived*>(this)->VisitCastExpr(E);
7496 }
7497 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7498 return static_cast<Derived*>(this)->VisitCastExpr(E);
7499 }
7500
7501 bool VisitBinaryOperator(const BinaryOperator *E) {
7502 switch (E->getOpcode()) {
7503 default:
7504 return Error(E);
7505
7506 case BO_Comma:
7507 VisitIgnoredValue(E->getLHS());
7508 return StmtVisitorTy::Visit(E->getRHS());
7509
7510 case BO_PtrMemD:
7511 case BO_PtrMemI: {
7512 LValue Obj;
7513 if (!HandleMemberPointerAccess(Info, E, Obj))
7514 return false;
7515 APValue Result;
7516 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7517 return false;
7518 return DerivedSuccess(Result, E);
7519 }
7520 }
7521 }
7522
7523 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7524 return StmtVisitorTy::Visit(E->getSemanticForm());
7525 }
7526
7527 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7528 // Evaluate and cache the common expression. We treat it as a temporary,
7529 // even though it's not quite the same thing.
7530 LValue CommonLV;
7531 if (!Evaluate(Info.CurrentCall->createTemporary(
7532 E->getOpaqueValue(),
7533 getStorageType(Info.Ctx, E->getOpaqueValue()),
7534 ScopeKind::FullExpression, CommonLV),
7535 Info, E->getCommon()))
7536 return false;
7537
7538 return HandleConditionalOperator(E);
7539 }
7540
7541 bool VisitConditionalOperator(const ConditionalOperator *E) {
7542 bool IsBcpCall = false;
7543 // If the condition (ignoring parens) is a __builtin_constant_p call,
7544 // the result is a constant expression if it can be folded without
7545 // side-effects. This is an important GNU extension. See GCC PR38377
7546 // for discussion.
7547 if (const CallExpr *CallCE =
7548 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7549 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7550 IsBcpCall = true;
7551
7552 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7553 // constant expression; we can't check whether it's potentially foldable.
7554 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7555 // it would return 'false' in this mode.
7556 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7557 return false;
7558
7559 FoldConstant Fold(Info, IsBcpCall);
7560 if (!HandleConditionalOperator(E)) {
7561 Fold.keepDiagnostics();
7562 return false;
7563 }
7564
7565 return true;
7566 }
7567
7568 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7569 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7570 return DerivedSuccess(*Value, E);
7571
7572 const Expr *Source = E->getSourceExpr();
7573 if (!Source)
7574 return Error(E);
7575 if (Source == E) {
7576 assert(0 && "OpaqueValueExpr recursively refers to itself")(static_cast <bool> (0 && "OpaqueValueExpr recursively refers to itself"
) ? void (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\""
, "clang/lib/AST/ExprConstant.cpp", 7576, __extension__ __PRETTY_FUNCTION__
))
;
7577 return Error(E);
7578 }
7579 return StmtVisitorTy::Visit(Source);
7580 }
7581
7582 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7583 for (const Expr *SemE : E->semantics()) {
7584 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7585 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7586 // result expression: there could be two different LValues that would
7587 // refer to the same object in that case, and we can't model that.
7588 if (SemE == E->getResultExpr())
7589 return Error(E);
7590
7591 // Unique OVEs get evaluated if and when we encounter them when
7592 // emitting the rest of the semantic form, rather than eagerly.
7593 if (OVE->isUnique())
7594 continue;
7595
7596 LValue LV;
7597 if (!Evaluate(Info.CurrentCall->createTemporary(
7598 OVE, getStorageType(Info.Ctx, OVE),
7599 ScopeKind::FullExpression, LV),
7600 Info, OVE->getSourceExpr()))
7601 return false;
7602 } else if (SemE == E->getResultExpr()) {
7603 if (!StmtVisitorTy::Visit(SemE))
7604 return false;
7605 } else {
7606 if (!EvaluateIgnoredValue(Info, SemE))
7607 return false;
7608 }
7609 }
7610 return true;
7611 }
7612
7613 bool VisitCallExpr(const CallExpr *E) {
7614 APValue Result;
7615 if (!handleCallExpr(E, Result, nullptr))
7616 return false;
7617 return DerivedSuccess(Result, E);
7618 }
7619
7620 bool handleCallExpr(const CallExpr *E, APValue &Result,
7621 const LValue *ResultSlot) {
7622 CallScopeRAII CallScope(Info);
7623
7624 const Expr *Callee = E->getCallee()->IgnoreParens();
7625 QualType CalleeType = Callee->getType();
7626
7627 const FunctionDecl *FD = nullptr;
7628 LValue *This = nullptr, ThisVal;
7629 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7630 bool HasQualifier = false;
7631
7632 CallRef Call;
7633
7634 // Extract function decl and 'this' pointer from the callee.
7635 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7636 const CXXMethodDecl *Member = nullptr;
7637 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7638 // Explicit bound member calls, such as x.f() or p->g();
7639 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7640 return false;
7641 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7642 if (!Member)
7643 return Error(Callee);
7644 This = &ThisVal;
7645 HasQualifier = ME->hasQualifier();
7646 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7647 // Indirect bound member calls ('.*' or '->*').
7648 const ValueDecl *D =
7649 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7650 if (!D)
7651 return false;
7652 Member = dyn_cast<CXXMethodDecl>(D);
7653 if (!Member)
7654 return Error(Callee);
7655 This = &ThisVal;
7656 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7657 if (!Info.getLangOpts().CPlusPlus20)
7658 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7659 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7660 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7661 } else
7662 return Error(Callee);
7663 FD = Member;
7664 } else if (CalleeType->isFunctionPointerType()) {
7665 LValue CalleeLV;
7666 if (!EvaluatePointer(Callee, CalleeLV, Info))
7667 return false;
7668
7669 if (!CalleeLV.getLValueOffset().isZero())
7670 return Error(Callee);
7671 if (CalleeLV.isNullPointer()) {
7672 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7673 << const_cast<Expr *>(Callee);
7674 return false;
7675 }
7676 FD = dyn_cast_or_null<FunctionDecl>(
7677 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7678 if (!FD)
7679 return Error(Callee);
7680 // Don't call function pointers which have been cast to some other type.
7681 // Per DR (no number yet), the caller and callee can differ in noexcept.
7682 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7683 CalleeType->getPointeeType(), FD->getType())) {
7684 return Error(E);
7685 }
7686
7687 // For an (overloaded) assignment expression, evaluate the RHS before the
7688 // LHS.
7689 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7690 if (OCE && OCE->isAssignmentOp()) {
7691 assert(Args.size() == 2 && "wrong number of arguments in assignment")(static_cast <bool> (Args.size() == 2 && "wrong number of arguments in assignment"
) ? void (0) : __assert_fail ("Args.size() == 2 && \"wrong number of arguments in assignment\""
, "clang/lib/AST/ExprConstant.cpp", 7691, __extension__ __PRETTY_FUNCTION__
))
;
7692 Call = Info.CurrentCall->createCall(FD);
7693 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7694 Info, FD, /*RightToLeft=*/true))
7695 return false;
7696 }
7697
7698 // Overloaded operator calls to member functions are represented as normal
7699 // calls with '*this' as the first argument.
7700 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7701 if (MD && !MD->isStatic()) {
7702 // FIXME: When selecting an implicit conversion for an overloaded
7703 // operator delete, we sometimes try to evaluate calls to conversion
7704 // operators without a 'this' parameter!
7705 if (Args.empty())
7706 return Error(E);
7707
7708 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7709 return false;
7710 This = &ThisVal;
7711
7712 // If this is syntactically a simple assignment using a trivial
7713 // assignment operator, start the lifetimes of union members as needed,
7714 // per C++20 [class.union]5.
7715 if (Info.getLangOpts().CPlusPlus20 && OCE &&
7716 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7717 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7718 return false;
7719
7720 Args = Args.slice(1);
7721 } else if (MD && MD->isLambdaStaticInvoker()) {
7722 // Map the static invoker for the lambda back to the call operator.
7723 // Conveniently, we don't have to slice out the 'this' argument (as is
7724 // being done for the non-static case), since a static member function
7725 // doesn't have an implicit argument passed in.
7726 const CXXRecordDecl *ClosureClass = MD->getParent();
7727 assert((static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "clang/lib/AST/ExprConstant.cpp", 7729, __extension__ __PRETTY_FUNCTION__
))
7728 ClosureClass->captures_begin() == ClosureClass->captures_end() &&(static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "clang/lib/AST/ExprConstant.cpp", 7729, __extension__ __PRETTY_FUNCTION__
))
7729 "Number of captures must be zero for conversion to function-ptr")(static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "clang/lib/AST/ExprConstant.cpp", 7729, __extension__ __PRETTY_FUNCTION__
))
;
7730
7731 const CXXMethodDecl *LambdaCallOp =
7732 ClosureClass->getLambdaCallOperator();
7733
7734 // Set 'FD', the function that will be called below, to the call
7735 // operator. If the closure object represents a generic lambda, find
7736 // the corresponding specialization of the call operator.
7737
7738 if (ClosureClass->isGenericLambda()) {
7739 assert(MD->isFunctionTemplateSpecialization() &&(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7741, __extension__ __PRETTY_FUNCTION__
))
7740 "A generic lambda's static-invoker function must be a "(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7741, __extension__ __PRETTY_FUNCTION__
))
7741 "template specialization")(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7741, __extension__ __PRETTY_FUNCTION__
))
;
7742 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7743 FunctionTemplateDecl *CallOpTemplate =
7744 LambdaCallOp->getDescribedFunctionTemplate();
7745 void *InsertPos = nullptr;
7746 FunctionDecl *CorrespondingCallOpSpecialization =
7747 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7748 assert(CorrespondingCallOpSpecialization &&(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7750, __extension__ __PRETTY_FUNCTION__
))
7749 "We must always have a function call operator specialization "(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7750, __extension__ __PRETTY_FUNCTION__
))
7750 "that corresponds to our static invoker specialization")(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "clang/lib/AST/ExprConstant.cpp", 7750, __extension__ __PRETTY_FUNCTION__
))
;
7751 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7752 } else
7753 FD = LambdaCallOp;
7754 } else if (FD->isReplaceableGlobalAllocationFunction()) {
7755 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7756 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7757 LValue Ptr;
7758 if (!HandleOperatorNewCall(Info, E, Ptr))
7759 return false;
7760 Ptr.moveInto(Result);
7761 return CallScope.destroy();
7762 } else {
7763 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7764 }
7765 }
7766 } else
7767 return Error(E);
7768
7769 // Evaluate the arguments now if we've not already done so.
7770 if (!Call) {
7771 Call = Info.CurrentCall->createCall(FD);
7772 if (!EvaluateArgs(Args, Call, Info, FD))
7773 return false;
7774 }
7775
7776 SmallVector<QualType, 4> CovariantAdjustmentPath;
7777 if (This) {
7778 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7779 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7780 // Perform virtual dispatch, if necessary.
7781 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7782 CovariantAdjustmentPath);
7783 if (!FD)
7784 return false;
7785 } else {
7786 // Check that the 'this' pointer points to an object of the right type.
7787 // FIXME: If this is an assignment operator call, we may need to change
7788 // the active union member before we check this.
7789 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7790 return false;
7791 }
7792 }
7793
7794 // Destructor calls are different enough that they have their own codepath.
7795 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7796 assert(This && "no 'this' pointer for destructor call")(static_cast <bool> (This && "no 'this' pointer for destructor call"
) ? void (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\""
, "clang/lib/AST/ExprConstant.cpp", 7796, __extension__ __PRETTY_FUNCTION__
))
;
7797 return HandleDestruction(Info, E, *This,
7798 Info.Ctx.getRecordType(DD->getParent())) &&
7799 CallScope.destroy();
7800 }
7801
7802 const FunctionDecl *Definition = nullptr;
7803 Stmt *Body = FD->getBody(Definition);
7804
7805 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7806 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7807 Body, Info, Result, ResultSlot))
7808 return false;
7809
7810 if (!CovariantAdjustmentPath.empty() &&
7811 !HandleCovariantReturnAdjustment(Info, E, Result,
7812 CovariantAdjustmentPath))
7813 return false;
7814
7815 return CallScope.destroy();
7816 }
7817
7818 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7819 return StmtVisitorTy::Visit(E->getInitializer());
7820 }
7821 bool VisitInitListExpr(const InitListExpr *E) {
7822 if (E->getNumInits() == 0)
7823 return DerivedZeroInitialization(E);
7824 if (E->getNumInits() == 1)
7825 return StmtVisitorTy::Visit(E->getInit(0));
7826 return Error(E);
7827 }
7828 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7829 return DerivedZeroInitialization(E);
7830 }
7831 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7832 return DerivedZeroInitialization(E);
7833 }
7834 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7835 return DerivedZeroInitialization(E);
7836 }
7837
7838 /// A member expression where the object is a prvalue is itself a prvalue.
7839 bool VisitMemberExpr(const MemberExpr *E) {
7840 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11
&& "missing temporary materialization conversion") ?
void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\""
, "clang/lib/AST/ExprConstant.cpp", 7841, __extension__ __PRETTY_FUNCTION__
))
7841 "missing temporary materialization conversion")(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11
&& "missing temporary materialization conversion") ?
void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\""
, "clang/lib/AST/ExprConstant.cpp", 7841, __extension__ __PRETTY_FUNCTION__
))
;
7842 assert(!E->isArrow() && "missing call to bound member function?")(static_cast <bool> (!E->isArrow() && "missing call to bound member function?"
) ? void (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\""
, "clang/lib/AST/ExprConstant.cpp", 7842, __extension__ __PRETTY_FUNCTION__
))
;
7843
7844 APValue Val;
7845 if (!Evaluate(Val, Info, E->getBase()))
7846 return false;
7847
7848 QualType BaseTy = E->getBase()->getType();
7849
7850 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7851 if (!FD) return Error(E);
7852 assert(!FD->getType()->isReferenceType() && "prvalue reference?")(static_cast <bool> (!FD->getType()->isReferenceType
() && "prvalue reference?") ? void (0) : __assert_fail
("!FD->getType()->isReferenceType() && \"prvalue reference?\""
, "clang/lib/AST/ExprConstant.cpp", 7852, __extension__ __PRETTY_FUNCTION__
))
;
7853 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "clang/lib/AST/ExprConstant.cpp", 7854, __extension__ __PRETTY_FUNCTION__
))
7854 FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "clang/lib/AST/ExprConstant.cpp", 7854, __extension__ __PRETTY_FUNCTION__
))
;
7855
7856 // Note: there is no lvalue base here. But this case should only ever
7857 // happen in C or in C++98, where we cannot be evaluating a constexpr
7858 // constructor, which is the only case the base matters.
7859 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7860 SubobjectDesignator Designator(BaseTy);
7861 Designator.addDeclUnchecked(FD);
7862
7863 APValue Result;
7864 return extractSubobject(Info, E, Obj, Designator, Result) &&
7865 DerivedSuccess(Result, E);
7866 }
7867
7868 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7869 APValue Val;
7870 if (!Evaluate(Val, Info, E->getBase()))
7871 return false;
7872
7873 if (Val.isVector()) {
7874 SmallVector<uint32_t, 4> Indices;
7875 E->getEncodedElementAccess(Indices);
7876 if (Indices.size() == 1) {
7877 // Return scalar.
7878 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7879 } else {
7880 // Construct new APValue vector.
7881 SmallVector<APValue, 4> Elts;
7882 for (unsigned I = 0; I < Indices.size(); ++I) {
7883 Elts.push_back(Val.getVectorElt(Indices[I]));
7884 }
7885 APValue VecResult(Elts.data(), Indices.size());
7886 return DerivedSuccess(VecResult, E);
7887 }
7888 }
7889
7890 return false;
7891 }
7892
7893 bool VisitCastExpr(const CastExpr *E) {
7894 switch (E->getCastKind()) {
7895 default:
7896 break;
7897
7898 case CK_AtomicToNonAtomic: {
7899 APValue AtomicVal;
7900 // This does not need to be done in place even for class/array types:
7901 // atomic-to-non-atomic conversion implies copying the object
7902 // representation.
7903 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7904 return false;
7905 return DerivedSuccess(AtomicVal, E);
7906 }
7907
7908 case CK_NoOp:
7909 case CK_UserDefinedConversion:
7910 return StmtVisitorTy::Visit(E->getSubExpr());
7911
7912 case CK_LValueToRValue: {
7913 LValue LVal;
7914 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7915 return false;
7916 APValue RVal;
7917 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7918 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7919 LVal, RVal))
7920 return false;
7921 return DerivedSuccess(RVal, E);
7922 }
7923 case CK_LValueToRValueBitCast: {
7924 APValue DestValue, SourceValue;
7925 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7926 return false;
7927 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7928 return false;
7929 return DerivedSuccess(DestValue, E);
7930 }
7931
7932 case CK_AddressSpaceConversion: {
7933 APValue Value;
7934 if (!Evaluate(Value, Info, E->getSubExpr()))
7935 return false;
7936 return DerivedSuccess(Value, E);
7937 }
7938 }
7939
7940 return Error(E);
7941 }
7942
7943 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7944 return VisitUnaryPostIncDec(UO);
7945 }
7946 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7947 return VisitUnaryPostIncDec(UO);
7948 }
7949 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7950 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7951 return Error(UO);
7952
7953 LValue LVal;
7954 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7955 return false;
7956 APValue RVal;
7957 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7958 UO->isIncrementOp(), &RVal))
7959 return false;
7960 return DerivedSuccess(RVal, UO);
7961 }
7962
7963 bool VisitStmtExpr(const StmtExpr *E) {
7964 // We will have checked the full-expressions inside the statement expression
7965 // when they were completed, and don't need to check them again now.
7966 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
7967 false);
7968
7969 const CompoundStmt *CS = E->getSubStmt();
7970 if (CS->body_empty())
7971 return true;
7972
7973 BlockScopeRAII Scope(Info);
7974 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7975 BE = CS->body_end();
7976 /**/; ++BI) {
7977 if (BI + 1 == BE) {
7978 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7979 if (!FinalExpr) {
7980 Info.FFDiag((*BI)->getBeginLoc(),
7981 diag::note_constexpr_stmt_expr_unsupported);
7982 return false;
7983 }
7984 return this->Visit(FinalExpr) && Scope.destroy();
7985 }
7986
7987 APValue ReturnValue;
7988 StmtResult Result = { ReturnValue, nullptr };
7989 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7990 if (ESR != ESR_Succeeded) {
7991 // FIXME: If the statement-expression terminated due to 'return',
7992 // 'break', or 'continue', it would be nice to propagate that to
7993 // the outer statement evaluation rather than bailing out.
7994 if (ESR != ESR_Failed)
7995 Info.FFDiag((*BI)->getBeginLoc(),
7996 diag::note_constexpr_stmt_expr_unsupported);
7997 return false;
7998 }
7999 }
8000
8001 llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above."
, "clang/lib/AST/ExprConstant.cpp", 8001)
;
8002 }
8003
8004 /// Visit a value which is evaluated, but whose value is ignored.
8005 void VisitIgnoredValue(const Expr *E) {
8006 EvaluateIgnoredValue(Info, E);
8007 }
8008
8009 /// Potentially visit a MemberExpr's base expression.
8010 void VisitIgnoredBaseExpression(const Expr *E) {
8011 // While MSVC doesn't evaluate the base expression, it does diagnose the
8012 // presence of side-effecting behavior.
8013 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8014 return;
8015 VisitIgnoredValue(E);
8016 }
8017};
8018
8019} // namespace
8020
8021//===----------------------------------------------------------------------===//
8022// Common base class for lvalue and temporary evaluation.
8023//===----------------------------------------------------------------------===//
8024namespace {
8025template<class Derived>
8026class LValueExprEvaluatorBase
8027 : public ExprEvaluatorBase<Derived> {
8028protected:
8029 LValue &Result;
8030 bool InvalidBaseOK;
8031 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8032 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8033
8034 bool Success(APValue::LValueBase B) {
8035 Result.set(B);
8036 return true;
8037 }
8038
8039 bool evaluatePointer(const Expr *E, LValue &Result) {
8040 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8041 }
8042
8043public:
8044 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8045 : ExprEvaluatorBaseTy(Info), Result(Result),
8046 InvalidBaseOK(InvalidBaseOK) {}
8047
8048 bool Success(const APValue &V, const Expr *E) {
8049 Result.setFrom(this->Info.Ctx, V);
8050 return true;
8051 }
8052
8053 bool VisitMemberExpr(const MemberExpr *E) {
8054 // Handle non-static data members.
8055 QualType BaseTy;
8056 bool EvalOK;
8057 if (E->isArrow()) {
8058 EvalOK = evaluatePointer(E->getBase(), Result);
8059 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8060 } else if (E->getBase()->isPRValue()) {
8061 assert(E->getBase()->getType()->isRecordType())(static_cast <bool> (E->getBase()->getType()->
isRecordType()) ? void (0) : __assert_fail ("E->getBase()->getType()->isRecordType()"
, "clang/lib/AST/ExprConstant.cpp", 8061, __extension__ __PRETTY_FUNCTION__
))
;
8062 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8063 BaseTy = E->getBase()->getType();
8064 } else {
8065 EvalOK = this->Visit(E->getBase());
8066 BaseTy = E->getBase()->getType();
8067 }
8068 if (!EvalOK) {
8069 if (!InvalidBaseOK)
8070 return false;
8071 Result.setInvalid(E);
8072 return true;
8073 }
8074
8075 const ValueDecl *MD = E->getMemberDecl();
8076 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8077 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "clang/lib/AST/ExprConstant.cpp", 8078, __extension__ __PRETTY_FUNCTION__
))
8078 FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "clang/lib/AST/ExprConstant.cpp", 8078, __extension__ __PRETTY_FUNCTION__
))
;
8079 (void)BaseTy;
8080 if (!HandleLValueMember(this->Info, E, Result, FD))
8081 return false;
8082 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8083 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8084 return false;
8085 } else
8086 return this->Error(E);
8087
8088 if (MD->getType()->isReferenceType()) {
8089 APValue RefValue;
8090 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8091 RefValue))
8092 return false;
8093 return Success(RefValue, E);
8094 }
8095 return true;
8096 }
8097
8098 bool VisitBinaryOperator(const BinaryOperator *E) {
8099 switch (E->getOpcode()) {
8100 default:
8101 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8102
8103 case BO_PtrMemD:
8104 case BO_PtrMemI:
8105 return HandleMemberPointerAccess(this->Info, E, Result);
8106 }
8107 }
8108
8109 bool VisitCastExpr(const CastExpr *E) {
8110 switch (E->getCastKind()) {
8111 default:
8112 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8113
8114 case CK_DerivedToBase:
8115 case CK_UncheckedDerivedToBase:
8116 if (!this->Visit(E->getSubExpr()))
8117 return false;
8118
8119 // Now figure out the necessary offset to add to the base LV to get from
8120 // the derived class to the base class.
8121 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8122 Result);
8123 }
8124 }
8125};
8126}
8127
8128//===----------------------------------------------------------------------===//
8129// LValue Evaluation
8130//
8131// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8132// function designators (in C), decl references to void objects (in C), and
8133// temporaries (if building with -Wno-address-of-temporary).
8134//
8135// LValue evaluation produces values comprising a base expression of one of the
8136// following types:
8137// - Declarations
8138// * VarDecl
8139// * FunctionDecl
8140// - Literals
8141// * CompoundLiteralExpr in C (and in global scope in C++)
8142// * StringLiteral
8143// * PredefinedExpr
8144// * ObjCStringLiteralExpr
8145// * ObjCEncodeExpr
8146// * AddrLabelExpr
8147// * BlockExpr
8148// * CallExpr for a MakeStringConstant builtin
8149// - typeid(T) expressions, as TypeInfoLValues
8150// - Locals and temporaries
8151// * MaterializeTemporaryExpr
8152// * Any Expr, with a CallIndex indicating the function in which the temporary
8153// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8154// from the AST (FIXME).
8155// * A MaterializeTemporaryExpr that has static storage duration, with no
8156// CallIndex, for a lifetime-extended temporary.
8157// * The ConstantExpr that is currently being evaluated during evaluation of an
8158// immediate invocation.
8159// plus an offset in bytes.
8160//===----------------------------------------------------------------------===//
8161namespace {
8162class LValueExprEvaluator
8163 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8164public:
8165 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8166 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8167
8168 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8169 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8170
8171 bool VisitCallExpr(const CallExpr *E);
8172 bool VisitDeclRefExpr(const DeclRefExpr *E);
8173 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8174 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8175 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8176 bool VisitMemberExpr(const MemberExpr *E);
8177 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8178 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8179 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8180 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8181 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8182 bool VisitUnaryDeref(const UnaryOperator *E);
8183 bool VisitUnaryReal(const UnaryOperator *E);
8184 bool VisitUnaryImag(const UnaryOperator *E);
8185 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8186 return VisitUnaryPreIncDec(UO);
8187 }
8188 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8189 return VisitUnaryPreIncDec(UO);
8190 }
8191 bool VisitBinAssign(const BinaryOperator *BO);
8192 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8193
8194 bool VisitCastExpr(const CastExpr *E) {
8195 switch (E->getCastKind()) {
8196 default:
8197 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8198
8199 case CK_LValueBitCast:
8200 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8201 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8202 if (!Visit(E->getSubExpr()))
8203 return false;
8204 Result.Designator.setInvalid();
8205 return true;
8206
8207 case CK_BaseToDerived:
8208 if (!Visit(E->getSubExpr()))
8209 return false;
8210 return HandleBaseToDerivedCast(Info, E, Result);
8211
8212 case CK_Dynamic:
8213 if (!Visit(E->getSubExpr()))
8214 return false;
8215 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8216 }
8217 }
8218};
8219} // end anonymous namespace
8220
8221/// Evaluate an expression as an lvalue. This can be legitimately called on
8222/// expressions which are not glvalues, in three cases:
8223/// * function designators in C, and
8224/// * "extern void" objects
8225/// * @selector() expressions in Objective-C
8226static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8227 bool InvalidBaseOK) {
8228 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 8228, __extension__ __PRETTY_FUNCTION__))
;
8229 assert(E->isGLValue() || E->getType()->isFunctionType() ||(static_cast <bool> (E->isGLValue() || E->getType
()->isFunctionType() || E->getType()->isVoidType() ||
isa<ObjCSelectorExpr>(E->IgnoreParens())) ? void (0
) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())"
, "clang/lib/AST/ExprConstant.cpp", 8230, __extension__ __PRETTY_FUNCTION__
))
8230 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()))(static_cast <bool> (E->isGLValue() || E->getType
()->isFunctionType() || E->getType()->isVoidType() ||
isa<ObjCSelectorExpr>(E->IgnoreParens())) ? void (0
) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())"
, "clang/lib/AST/ExprConstant.cpp", 8230, __extension__ __PRETTY_FUNCTION__
))
;
8231 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8232}
8233
8234bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8235 const NamedDecl *D = E->getDecl();
8236 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8237 UnnamedGlobalConstantDecl>(D))
8238 return Success(cast<ValueDecl>(D));
8239 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8240 return VisitVarDecl(E, VD);
8241 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8242 return Visit(BD->getBinding());
8243 return Error(E);
8244}
8245
8246
8247bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8248
8249 // If we are within a lambda's call operator, check whether the 'VD' referred
8250 // to within 'E' actually represents a lambda-capture that maps to a
8251 // data-member/field within the closure object, and if so, evaluate to the
8252 // field or what the field refers to.
8253 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
4
Assuming field 'CurrentCall' is null
8254 isa<DeclRefExpr>(E) &&
8255 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8256 // We don't always have a complete capture-map when checking or inferring if
8257 // the function call operator meets the requirements of a constexpr function
8258 // - but we don't need to evaluate the captures to determine constexprness
8259 // (dcl.constexpr C++17).
8260 if (Info.checkingPotentialConstantExpression())
8261 return false;
8262
8263 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8264 // Start with 'Result' referring to the complete closure object...
8265 Result = *Info.CurrentCall->This;
8266 // ... then update it to refer to the field of the closure object
8267 // that represents the capture.
8268 if (!HandleLValueMember(Info, E, Result, FD))
8269 return false;
8270 // And if the field is of reference type, update 'Result' to refer to what
8271 // the field refers to.
8272 if (FD->getType()->isReferenceType()) {
8273 APValue RVal;
8274 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8275 RVal))
8276 return false;
8277 Result.setFrom(Info.Ctx, RVal);
8278 }
8279 return true;
8280 }
8281 }
8282
8283 CallStackFrame *Frame = nullptr;
8284 unsigned Version = 0;
8285 if (VD->hasLocalStorage()) {
5
Taking false branch
8286 // Only if a local variable was declared in the function currently being
8287 // evaluated, do we expect to be able to find its value in the current
8288 // frame. (Otherwise it was likely declared in an enclosing context and
8289 // could either have a valid evaluatable value (for e.g. a constexpr
8290 // variable) or be ill-formed (and trigger an appropriate evaluation
8291 // diagnostic)).
8292 CallStackFrame *CurrFrame = Info.CurrentCall;
8293 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8294 // Function parameters are stored in some caller's frame. (Usually the
8295 // immediate caller, but for an inherited constructor they may be more
8296 // distant.)
8297 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8298 if (CurrFrame->Arguments) {
8299 VD = CurrFrame->Arguments.getOrigParam(PVD);
8300 Frame =
8301 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8302 Version = CurrFrame->Arguments.Version;
8303 }
8304 } else {
8305 Frame = CurrFrame;
8306 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8307 }
8308 }
8309 }
8310
8311 if (!VD->getType()->isReferenceType()) {
6
Taking false branch
8312 if (Frame) {
8313 Result.set({VD, Frame->Index, Version});
8314 return true;
8315 }
8316 return Success(VD);
8317 }
8318
8319 if (!Info.getLangOpts().CPlusPlus11) {
7
Assuming field 'CPlusPlus11' is not equal to 0
8
Taking false branch
8320 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8321 << VD << VD->getType();
8322 Info.Note(VD->getLocation(), diag::note_declared_at);
8323 }
8324
8325 APValue *V;
8326 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9
Calling 'evaluateVarDeclInit'
8327 return false;
8328 if (!V->hasValue()) {
8329 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8330 // adjust the diagnostic to say that.
8331 if (!Info.checkingPotentialConstantExpression())
8332 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8333 return false;
8334 }
8335 return Success(*V, E);
8336}
8337
8338bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8339 if (!IsConstantEvaluatedBuiltinCall(E))
8340 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8341
8342 switch (E->getBuiltinCallee()) {
8343 default:
8344 return false;
8345 case Builtin::BIas_const:
8346 case Builtin::BIforward:
8347 case Builtin::BIforward_like:
8348 case Builtin::BImove:
8349 case Builtin::BImove_if_noexcept:
8350 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8351 return Visit(E->getArg(0));
8352 break;
8353 }
8354
8355 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8356}
8357
8358bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8359 const MaterializeTemporaryExpr *E) {
8360 // Walk through the expression to find the materialized temporary itself.
8361 SmallVector<const Expr *, 2> CommaLHSs;
8362 SmallVector<SubobjectAdjustment, 2> Adjustments;
8363 const Expr *Inner =
8364 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8365
8366 // If we passed any comma operators, evaluate their LHSs.
8367 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8368 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8369 return false;
8370
8371 // A materialized temporary with static storage duration can appear within the
8372 // result of a constant expression evaluation, so we need to preserve its
8373 // value for use outside this evaluation.
8374 APValue *Value;
8375 if (E->getStorageDuration() == SD_Static) {
8376 // FIXME: What about SD_Thread?
8377 Value = E->getOrCreateValue(true);
8378 *Value = APValue();
8379 Result.set(E);
8380 } else {
8381 Value = &Info.CurrentCall->createTemporary(
8382 E, E->getType(),
8383 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8384 : ScopeKind::Block,
8385 Result);
8386 }
8387
8388 QualType Type = Inner->getType();
8389
8390 // Materialize the temporary itself.
8391 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8392 *Value = APValue();
8393 return false;
8394 }
8395
8396 // Adjust our lvalue to refer to the desired subobject.
8397 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8398 --I;
8399 switch (Adjustments[I].Kind) {
8400 case SubobjectAdjustment::DerivedToBaseAdjustment:
8401 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8402 Type, Result))
8403 return false;
8404 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8405 break;
8406
8407 case SubobjectAdjustment::FieldAdjustment:
8408 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8409 return false;
8410 Type = Adjustments[I].Field->getType();
8411 break;
8412
8413 case SubobjectAdjustment::MemberPointerAdjustment:
8414 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8415 Adjustments[I].Ptr.RHS))
8416 return false;
8417 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8418 break;
8419 }
8420 }
8421
8422 return true;
8423}
8424
8425bool
8426LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8427 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E
->isFileScope()) && "lvalue compound literal in c++?"
) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "clang/lib/AST/ExprConstant.cpp", 8428, __extension__ __PRETTY_FUNCTION__
))
8428 "lvalue compound literal in c++?")(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E
->isFileScope()) && "lvalue compound literal in c++?"
) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "clang/lib/AST/ExprConstant.cpp", 8428, __extension__ __PRETTY_FUNCTION__
))
;
8429 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8430 // only see this when folding in C, so there's no standard to follow here.
8431 return Success(E);
8432}
8433
8434bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8435 TypeInfoLValue TypeInfo;
8436
8437 if (!E->isPotentiallyEvaluated()) {
8438 if (E->isTypeOperand())
8439 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8440 else
8441 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8442 } else {
8443 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8444 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8445 << E->getExprOperand()->getType()
8446 << E->getExprOperand()->getSourceRange();
8447 }
8448
8449 if (!Visit(E->getExprOperand()))
8450 return false;
8451
8452 std::optional<DynamicType> DynType =
8453 ComputeDynamicType(Info, E, Result, AK_TypeId);
8454 if (!DynType)
8455 return false;
8456
8457 TypeInfo =
8458 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8459 }
8460
8461 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8462}
8463
8464bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8465 return Success(E->getGuidDecl());
8466}
8467
8468bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8469 // Handle static data members.
8470 if (const VarDecl *VD
1.1
'VD' is non-null
= dyn_cast<VarDecl>(E->getMemberDecl())) {
1
Assuming the object is a 'CastReturnType'
2
Taking true branch
8471 VisitIgnoredBaseExpression(E->getBase());
8472 return VisitVarDecl(E, VD);
3
Calling 'LValueExprEvaluator::VisitVarDecl'
8473 }
8474
8475 // Handle static member functions.
8476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8477 if (MD->isStatic()) {
8478 VisitIgnoredBaseExpression(E->getBase());
8479 return Success(MD);
8480 }
8481 }
8482
8483 // Handle non-static data members.
8484 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8485}
8486
8487bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8488 // FIXME: Deal with vectors as array subscript bases.
8489 if (E->getBase()->getType()->isVectorType() ||
8490 E->getBase()->getType()->isVLSTBuiltinType())
8491 return Error(E);
8492
8493 APSInt Index;
8494 bool Success = true;
8495
8496 // C++17's rules require us to evaluate the LHS first, regardless of which
8497 // side is the base.
8498 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8499 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8500 : !EvaluateInteger(SubExpr, Index, Info)) {
8501 if (!Info.noteFailure())
8502 return false;
8503 Success = false;
8504 }
8505 }
8506
8507 return Success &&
8508 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8509}
8510
8511bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8512 return evaluatePointer(E->getSubExpr(), Result);
8513}
8514
8515bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8516 if (!Visit(E->getSubExpr()))
8517 return false;
8518 // __real is a no-op on scalar lvalues.
8519 if (E->getSubExpr()->getType()->isAnyComplexType())
8520 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8521 return true;
8522}
8523
8524bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8525 assert(E->getSubExpr()->getType()->isAnyComplexType() &&(static_cast <bool> (E->getSubExpr()->getType()->
isAnyComplexType() && "lvalue __imag__ on scalar?") ?
void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "clang/lib/AST/ExprConstant.cpp", 8526, __extension__ __PRETTY_FUNCTION__
))
8526 "lvalue __imag__ on scalar?")(static_cast <bool> (E->getSubExpr()->getType()->
isAnyComplexType() && "lvalue __imag__ on scalar?") ?
void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "clang/lib/AST/ExprConstant.cpp", 8526, __extension__ __PRETTY_FUNCTION__
))
;
8527 if (!Visit(E->getSubExpr()))
8528 return false;
8529 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8530 return true;
8531}
8532
8533bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8534 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8535 return Error(UO);
8536
8537 if (!this->Visit(UO->getSubExpr()))
8538 return false;
8539
8540 return handleIncDec(
8541 this->Info, UO, Result, UO->getSubExpr()->getType(),
8542 UO->isIncrementOp(), nullptr);
8543}
8544
8545bool LValueExprEvaluator::VisitCompoundAssignOperator(
8546 const CompoundAssignOperator *CAO) {
8547 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8548 return Error(CAO);
8549
8550 bool Success = true;
8551
8552 // C++17 onwards require that we evaluate the RHS first.
8553 APValue RHS;
8554 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8555 if (!Info.noteFailure())
8556 return false;
8557 Success = false;
8558 }
8559
8560 // The overall lvalue result is the result of evaluating the LHS.
8561 if (!this->Visit(CAO->getLHS()) || !Success)
8562 return false;
8563
8564 return handleCompoundAssignment(
8565 this->Info, CAO,
8566 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8567 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8568}
8569
8570bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8571 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8572 return Error(E);
8573
8574 bool Success = true;
8575
8576 // C++17 onwards require that we evaluate the RHS first.
8577 APValue NewVal;
8578 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8579 if (!Info.noteFailure())
8580 return false;
8581 Success = false;
8582 }
8583
8584 if (!this->Visit(E->getLHS()) || !Success)
8585 return false;
8586
8587 if (Info.getLangOpts().CPlusPlus20 &&
8588 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8589 return false;
8590
8591 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8592 NewVal);
8593}
8594
8595//===----------------------------------------------------------------------===//
8596// Pointer Evaluation
8597//===----------------------------------------------------------------------===//
8598
8599/// Attempts to compute the number of bytes available at the pointer
8600/// returned by a function with the alloc_size attribute. Returns true if we
8601/// were successful. Places an unsigned number into `Result`.
8602///
8603/// This expects the given CallExpr to be a call to a function with an
8604/// alloc_size attribute.
8605static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8606 const CallExpr *Call,
8607 llvm::APInt &Result) {
8608 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8609
8610 assert(AllocSize && AllocSize->getElemSizeParam().isValid())(static_cast <bool> (AllocSize && AllocSize->
getElemSizeParam().isValid()) ? void (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()"
, "clang/lib/AST/ExprConstant.cpp", 8610, __extension__ __PRETTY_FUNCTION__
))
;
8611 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8612 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8613 if (Call->getNumArgs() <= SizeArgNo)
8614 return false;
8615
8616 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8617 Expr::EvalResult ExprResult;
8618 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8619 return false;
8620 Into = ExprResult.Val.getInt();
8621 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8622 return false;
8623 Into = Into.zext(BitsInSizeT);
8624 return true;
8625 };
8626
8627 APSInt SizeOfElem;
8628 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8629 return false;
8630
8631 if (!AllocSize->getNumElemsParam().isValid()) {
8632 Result = std::move(SizeOfElem);
8633 return true;
8634 }
8635
8636 APSInt NumberOfElems;
8637 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8638 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8639 return false;
8640
8641 bool Overflow;
8642 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8643 if (Overflow)
8644 return false;
8645
8646 Result = std::move(BytesAvailable);
8647 return true;
8648}
8649
8650/// Convenience function. LVal's base must be a call to an alloc_size
8651/// function.
8652static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8653 const LValue &LVal,
8654 llvm::APInt &Result) {
8655 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase
()) && "Can't get the size of a non alloc_size function"
) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "clang/lib/AST/ExprConstant.cpp", 8656, __extension__ __PRETTY_FUNCTION__
))
8656 "Can't get the size of a non alloc_size function")(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase
()) && "Can't get the size of a non alloc_size function"
) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "clang/lib/AST/ExprConstant.cpp", 8656, __extension__ __PRETTY_FUNCTION__
))
;
8657 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8658 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8659 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8660}
8661
8662/// Attempts to evaluate the given LValueBase as the result of a call to
8663/// a function with the alloc_size attribute. If it was possible to do so, this
8664/// function will return true, make Result's Base point to said function call,
8665/// and mark Result's Base as invalid.
8666static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8667 LValue &Result) {
8668 if (Base.isNull())
8669 return false;
8670
8671 // Because we do no form of static analysis, we only support const variables.
8672 //
8673 // Additionally, we can't support parameters, nor can we support static
8674 // variables (in the latter case, use-before-assign isn't UB; in the former,
8675 // we have no clue what they'll be assigned to).
8676 const auto *VD =
8677 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8678 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8679 return false;
8680
8681 const Expr *Init = VD->getAnyInitializer();
8682 if (!Init || Init->getType().isNull())
8683 return false;
8684
8685 const Expr *E = Init->IgnoreParens();
8686 if (!tryUnwrapAllocSizeCall(E))
8687 return false;
8688
8689 // Store E instead of E unwrapped so that the type of the LValue's base is
8690 // what the user wanted.
8691 Result.setInvalid(E);
8692
8693 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8694 Result.addUnsizedArray(Info, E, Pointee);
8695 return true;
8696}
8697
8698namespace {
8699class PointerExprEvaluator
8700 : public ExprEvaluatorBase<PointerExprEvaluator> {
8701 LValue &Result;
8702 bool InvalidBaseOK;
8703
8704 bool Success(const Expr *E) {
8705 Result.set(E);
8706 return true;
8707 }
8708
8709 bool evaluateLValue(const Expr *E, LValue &Result) {
8710 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8711 }
8712
8713 bool evaluatePointer(const Expr *E, LValue &Result) {
8714 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8715 }
8716
8717 bool visitNonBuiltinCallExpr(const CallExpr *E);
8718public:
8719
8720 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8721 : ExprEvaluatorBaseTy(info), Result(Result),
8722 InvalidBaseOK(InvalidBaseOK) {}
8723
8724 bool Success(const APValue &V, const Expr *E) {
8725 Result.setFrom(Info.Ctx, V);
8726 return true;
8727 }
8728 bool ZeroInitialization(const Expr *E) {
8729 Result.setNull(Info.Ctx, E->getType());
8730 return true;
8731 }
8732
8733 bool VisitBinaryOperator(const BinaryOperator *E);
8734 bool VisitCastExpr(const CastExpr* E);
8735 bool VisitUnaryAddrOf(const UnaryOperator *E);
8736 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8737 { return Success(E); }
8738 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8739 if (E->isExpressibleAsConstantInitializer())
8740 return Success(E);
8741 if (Info.noteFailure())
8742 EvaluateIgnoredValue(Info, E->getSubExpr());
8743 return Error(E);
8744 }
8745 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8746 { return Success(E); }
8747 bool VisitCallExpr(const CallExpr *E);
8748 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8749 bool VisitBlockExpr(const BlockExpr *E) {
8750 if (!E->getBlockDecl()->hasCaptures())
8751 return Success(E);
8752 return Error(E);
8753 }
8754 bool VisitCXXThisExpr(const CXXThisExpr *E) {
8755 // Can't look at 'this' when checking a potential constant expression.
8756 if (Info.checkingPotentialConstantExpression())
8757 return false;
8758 if (!Info.CurrentCall->This) {
8759 if (Info.getLangOpts().CPlusPlus11)
8760 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8761 else
8762 Info.FFDiag(E);
8763 return false;
8764 }
8765 Result = *Info.CurrentCall->This;
8766
8767 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8768 // Ensure we actually have captured 'this'. If something was wrong with
8769 // 'this' capture, the error would have been previously reported.
8770 // Otherwise we can be inside of a default initialization of an object
8771 // declared by lambda's body, so no need to return false.
8772 if (!Info.CurrentCall->LambdaThisCaptureField)
8773 return true;
8774
8775 // If we have captured 'this', the 'this' expression refers
8776 // to the enclosing '*this' object (either by value or reference) which is
8777 // either copied into the closure object's field that represents the
8778 // '*this' or refers to '*this'.
8779 // Update 'Result' to refer to the data member/field of the closure object
8780 // that represents the '*this' capture.
8781 if (!HandleLValueMember(Info, E, Result,
8782 Info.CurrentCall->LambdaThisCaptureField))
8783 return false;
8784 // If we captured '*this' by reference, replace the field with its referent.
8785 if (Info.CurrentCall->LambdaThisCaptureField->getType()
8786 ->isPointerType()) {
8787 APValue RVal;
8788 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8789 RVal))
8790 return false;
8791
8792 Result.setFrom(Info.Ctx, RVal);
8793 }
8794 }
8795 return true;
8796 }
8797
8798 bool VisitCXXNewExpr(const CXXNewExpr *E);
8799
8800 bool VisitSourceLocExpr(const SourceLocExpr *E) {
8801 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?")(static_cast <bool> (!E->isIntType() && "SourceLocExpr isn't a pointer type?"
) ? void (0) : __assert_fail ("!E->isIntType() && \"SourceLocExpr isn't a pointer type?\""
, "clang/lib/AST/ExprConstant.cpp", 8801, __extension__ __PRETTY_FUNCTION__
))
;
8802 APValue LValResult = E->EvaluateInContext(
8803 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8804 Result.setFrom(Info.Ctx, LValResult);
8805 return true;
8806 }
8807
8808 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8809 std::string ResultStr = E->ComputeName(Info.Ctx);
8810
8811 QualType CharTy = Info.Ctx.CharTy.withConst();
8812 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8813 ResultStr.size() + 1);
8814 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8815 ArrayType::Normal, 0);
8816
8817 StringLiteral *SL =
8818 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8819 /*Pascal*/ false, ArrayTy, E->getLocation());
8820
8821 evaluateLValue(SL, Result);
8822 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8823 return true;
8824 }
8825
8826 // FIXME: Missing: @protocol, @selector
8827};
8828} // end anonymous namespace
8829
8830static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8831 bool InvalidBaseOK) {
8832 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 8832, __extension__ __PRETTY_FUNCTION__))
;
8833 assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E->
getType()->hasPointerRepresentation()) ? void (0) : __assert_fail
("E->isPRValue() && E->getType()->hasPointerRepresentation()"
, "clang/lib/AST/ExprConstant.cpp", 8833, __extension__ __PRETTY_FUNCTION__
))
;
8834 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8835}
8836
8837bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8838 if (E->getOpcode() != BO_Add &&
8839 E->getOpcode() != BO_Sub)
8840 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8841
8842 const Expr *PExp = E->getLHS();
8843 const Expr *IExp = E->getRHS();
8844 if (IExp->getType()->isPointerType())
8845 std::swap(PExp, IExp);
8846
8847 bool EvalPtrOK = evaluatePointer(PExp, Result);
8848 if (!EvalPtrOK && !Info.noteFailure())
8849 return false;
8850
8851 llvm::APSInt Offset;
8852 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8853 return false;
8854
8855 if (E->getOpcode() == BO_Sub)
8856 negateAsSigned(Offset);
8857
8858 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8859 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8860}
8861
8862bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8863 return evaluateLValue(E->getSubExpr(), Result);
8864}
8865
8866// Is the provided decl 'std::source_location::current'?
8867static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8868 if (!FD)
8869 return false;
8870 const IdentifierInfo *FnII = FD->getIdentifier();
8871 if (!FnII || !FnII->isStr("current"))
8872 return false;
8873
8874 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8875 if (!RD)
8876 return false;
8877
8878 const IdentifierInfo *ClassII = RD->getIdentifier();
8879 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8880}
8881
8882bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8883 const Expr *SubExpr = E->getSubExpr();
8884
8885 switch (E->getCastKind()) {
8886 default:
8887 break;
8888 case CK_BitCast:
8889 case CK_CPointerToObjCPointerCast:
8890 case CK_BlockPointerToObjCPointerCast:
8891 case CK_AnyPointerToBlockPointerCast:
8892 case CK_AddressSpaceConversion:
8893 if (!Visit(SubExpr))
8894 return false;
8895 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8896 // permitted in constant expressions in C++11. Bitcasts from cv void* are
8897 // also static_casts, but we disallow them as a resolution to DR1312.
8898 if (!E->getType()->isVoidPointerType()) {
8899 // In some circumstances, we permit casting from void* to cv1 T*, when the
8900 // actual pointee object is actually a cv2 T.
8901 bool VoidPtrCastMaybeOK =
8902 !Result.InvalidBase && !Result.Designator.Invalid &&
8903 !Result.IsNullPtr &&
8904 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8905 E->getType()->getPointeeType());
8906 // 1. We'll allow it in std::allocator::allocate, and anything which that
8907 // calls.
8908 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8909 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8910 // We'll allow it in the body of std::source_location::current. GCC's
8911 // implementation had a parameter of type `void*`, and casts from
8912 // that back to `const __impl*` in its body.
8913 if (VoidPtrCastMaybeOK &&
8914 (Info.getStdAllocatorCaller("allocate") ||
8915 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8916 // Permitted.
8917 } else {
8918 Result.Designator.setInvalid();
8919 if (SubExpr->getType()->isVoidPointerType())
8920 CCEDiag(E, diag::note_constexpr_invalid_cast)
8921 << 3 << SubExpr->getType();
8922 else
8923 CCEDiag(E, diag::note_constexpr_invalid_cast)
8924 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8925 }
8926 }
8927 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8928 ZeroInitialization(E);
8929 return true;
8930
8931 case CK_DerivedToBase:
8932 case CK_UncheckedDerivedToBase:
8933 if (!evaluatePointer(E->getSubExpr(), Result))
8934 return false;
8935 if (!Result.Base && Result.Offset.isZero())
8936 return true;
8937
8938 // Now figure out the necessary offset to add to the base LV to get from
8939 // the derived class to the base class.
8940 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8941 castAs<PointerType>()->getPointeeType(),
8942 Result);
8943
8944 case CK_BaseToDerived:
8945 if (!Visit(E->getSubExpr()))
8946 return false;
8947 if (!Result.Base && Result.Offset.isZero())
8948 return true;
8949 return HandleBaseToDerivedCast(Info, E, Result);
8950
8951 case CK_Dynamic:
8952 if (!Visit(E->getSubExpr()))
8953 return false;
8954 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8955
8956 case CK_NullToPointer:
8957 VisitIgnoredValue(E->getSubExpr());
8958 return ZeroInitialization(E);
8959
8960 case CK_IntegralToPointer: {
8961 CCEDiag(E, diag::note_constexpr_invalid_cast)
8962 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8963
8964 APValue Value;
8965 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8966 break;
8967
8968 if (Value.isInt()) {
8969 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8970 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8971 Result.Base = (Expr*)nullptr;
8972 Result.InvalidBase = false;
8973 Result.Offset = CharUnits::fromQuantity(N);
8974 Result.Designator.setInvalid();
8975 Result.IsNullPtr = false;
8976 return true;
8977 } else {
8978 // Cast is of an lvalue, no need to change value.
8979 Result.setFrom(Info.Ctx, Value);
8980 return true;
8981 }
8982 }
8983
8984 case CK_ArrayToPointerDecay: {
8985 if (SubExpr->isGLValue()) {
8986 if (!evaluateLValue(SubExpr, Result))
8987 return false;
8988 } else {
8989 APValue &Value = Info.CurrentCall->createTemporary(
8990 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8991 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8992 return false;
8993 }
8994 // The result is a pointer to the first element of the array.
8995 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8996 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8997 Result.addArray(Info, E, CAT);
8998 else
8999 Result.addUnsizedArray(Info, E, AT->getElementType());
9000 return true;
9001 }
9002
9003 case CK_FunctionToPointerDecay:
9004 return evaluateLValue(SubExpr, Result);
9005
9006 case CK_LValueToRValue: {
9007 LValue LVal;
9008 if (!evaluateLValue(E->getSubExpr(), LVal))
9009 return false;
9010
9011 APValue RVal;
9012 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9013 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9014 LVal, RVal))
9015 return InvalidBaseOK &&
9016 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9017 return Success(RVal, E);
9018 }
9019 }
9020
9021 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9022}
9023
9024static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9025 UnaryExprOrTypeTrait ExprKind) {
9026 // C++ [expr.alignof]p3:
9027 // When alignof is applied to a reference type, the result is the
9028 // alignment of the referenced type.
9029 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9030 T = Ref->getPointeeType();
9031
9032 if (T.getQualifiers().hasUnaligned())
9033 return CharUnits::One();
9034
9035 const bool AlignOfReturnsPreferred =
9036 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9037
9038 // __alignof is defined to return the preferred alignment.
9039 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9040 // as well.
9041 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9042 return Info.Ctx.toCharUnitsFromBits(
9043 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9044 // alignof and _Alignof are defined to return the ABI alignment.
9045 else if (ExprKind == UETT_AlignOf)
9046 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9047 else
9048 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind"
, "clang/lib/AST/ExprConstant.cpp", 9048)
;
9049}
9050
9051static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9052 UnaryExprOrTypeTrait ExprKind) {
9053 E = E->IgnoreParens();
9054
9055 // The kinds of expressions that we have special-case logic here for
9056 // should be kept up to date with the special checks for those
9057 // expressions in Sema.
9058
9059 // alignof decl is always accepted, even if it doesn't make sense: we default
9060 // to 1 in those cases.
9061 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9062 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9063 /*RefAsPointee*/true);
9064
9065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9066 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9067 /*RefAsPointee*/true);
9068
9069 return GetAlignOfType(Info, E->getType(), ExprKind);
9070}
9071
9072static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9073 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9074 return Info.Ctx.getDeclAlign(VD);
9075 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9076 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9077 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9078}
9079
9080/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9081/// __builtin_is_aligned and __builtin_assume_aligned.
9082static bool getAlignmentArgument(const Expr *E, QualType ForType,
9083 EvalInfo &Info, APSInt &Alignment) {
9084 if (!EvaluateInteger(E, Alignment, Info))
9085 return false;
9086 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9087 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9088 return false;
9089 }
9090 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9091 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9092 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9093 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9094 << MaxValue << ForType << Alignment;
9095 return false;
9096 }
9097 // Ensure both alignment and source value have the same bit width so that we
9098 // don't assert when computing the resulting value.
9099 APSInt ExtAlignment =
9100 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9101 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment
) == 0 && "Alignment should not be changed by ext/trunc"
) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\""
, "clang/lib/AST/ExprConstant.cpp", 9102, __extension__ __PRETTY_FUNCTION__
))
9102 "Alignment should not be changed by ext/trunc")(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment
) == 0 && "Alignment should not be changed by ext/trunc"
) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\""
, "clang/lib/AST/ExprConstant.cpp", 9102, __extension__ __PRETTY_FUNCTION__
))
;
9103 Alignment = ExtAlignment;
9104 assert(Alignment.getBitWidth() == SrcWidth)(static_cast <bool> (Alignment.getBitWidth() == SrcWidth
) ? void (0) : __assert_fail ("Alignment.getBitWidth() == SrcWidth"
, "clang/lib/AST/ExprConstant.cpp", 9104, __extension__ __PRETTY_FUNCTION__
))
;
9105 return true;
9106}
9107
9108// To be clear: this happily visits unsupported builtins. Better name welcomed.
9109bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9110 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9111 return true;
9112
9113 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9114 return false;
9115
9116 Result.setInvalid(E);
9117 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9118 Result.addUnsizedArray(Info, E, PointeeTy);
9119 return true;
9120}
9121
9122bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9123 if (!IsConstantEvaluatedBuiltinCall(E))
9124 return visitNonBuiltinCallExpr(E);
9125 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9126}
9127
9128// Determine if T is a character type for which we guarantee that
9129// sizeof(T) == 1.
9130static bool isOneByteCharacterType(QualType T) {
9131 return T->isCharType() || T->isChar8Type();
9132}
9133
9134bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9135 unsigned BuiltinOp) {
9136 if (IsNoOpCall(E))
9137 return Success(E);
9138
9139 switch (BuiltinOp) {
9140 case Builtin::BIaddressof:
9141 case Builtin::BI__addressof:
9142 case Builtin::BI__builtin_addressof:
9143 return evaluateLValue(E->getArg(0), Result);
9144 case Builtin::BI__builtin_assume_aligned: {
9145 // We need to be very careful here because: if the pointer does not have the
9146 // asserted alignment, then the behavior is undefined, and undefined
9147 // behavior is non-constant.
9148 if (!evaluatePointer(E->getArg(0), Result))
9149 return false;
9150
9151 LValue OffsetResult(Result);
9152 APSInt Alignment;
9153 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9154 Alignment))
9155 return false;
9156 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9157
9158 if (E->getNumArgs() > 2) {
9159 APSInt Offset;
9160 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9161 return false;
9162
9163 int64_t AdditionalOffset = -Offset.getZExtValue();
9164 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9165 }
9166
9167 // If there is a base object, then it must have the correct alignment.
9168 if (OffsetResult.Base) {
9169 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9170
9171 if (BaseAlignment < Align) {
9172 Result.Designator.setInvalid();
9173 // FIXME: Add support to Diagnostic for long / long long.
9174 CCEDiag(E->getArg(0),
9175 diag::note_constexpr_baa_insufficient_alignment) << 0
9176 << (unsigned)BaseAlignment.getQuantity()
9177 << (unsigned)Align.getQuantity();
9178 return false;
9179 }
9180 }
9181
9182 // The offset must also have the correct alignment.
9183 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9184 Result.Designator.setInvalid();
9185
9186 (OffsetResult.Base
9187 ? CCEDiag(E->getArg(0),
9188 diag::note_constexpr_baa_insufficient_alignment) << 1
9189 : CCEDiag(E->getArg(0),
9190 diag::note_constexpr_baa_value_insufficient_alignment))
9191 << (int)OffsetResult.Offset.getQuantity()
9192 << (unsigned)Align.getQuantity();
9193 return false;
9194 }
9195
9196 return true;
9197 }
9198 case Builtin::BI__builtin_align_up:
9199 case Builtin::BI__builtin_align_down: {
9200 if (!evaluatePointer(E->getArg(0), Result))
9201 return false;
9202 APSInt Alignment;
9203 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9204 Alignment))
9205 return false;
9206 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9207 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9208 // For align_up/align_down, we can return the same value if the alignment
9209 // is known to be greater or equal to the requested value.
9210 if (PtrAlign.getQuantity() >= Alignment)
9211 return true;
9212
9213 // The alignment could be greater than the minimum at run-time, so we cannot
9214 // infer much about the resulting pointer value. One case is possible:
9215 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9216 // can infer the correct index if the requested alignment is smaller than
9217 // the base alignment so we can perform the computation on the offset.
9218 if (BaseAlignment.getQuantity() >= Alignment) {
9219 assert(Alignment.getBitWidth() <= 64 &&(static_cast <bool> (Alignment.getBitWidth() <= 64 &&
"Cannot handle > 64-bit address-space") ? void (0) : __assert_fail
("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\""
, "clang/lib/AST/ExprConstant.cpp", 9220, __extension__ __PRETTY_FUNCTION__
))
9220 "Cannot handle > 64-bit address-space")(static_cast <bool> (Alignment.getBitWidth() <= 64 &&
"Cannot handle > 64-bit address-space") ? void (0) : __assert_fail
("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\""
, "clang/lib/AST/ExprConstant.cpp", 9220, __extension__ __PRETTY_FUNCTION__
))
;
9221 uint64_t Alignment64 = Alignment.getZExtValue();
9222 CharUnits NewOffset = CharUnits::fromQuantity(
9223 BuiltinOp == Builtin::BI__builtin_align_down
9224 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9225 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9226 Result.adjustOffset(NewOffset - Result.Offset);
9227 // TODO: diagnose out-of-bounds values/only allow for arrays?
9228 return true;
9229 }
9230 // Otherwise, we cannot constant-evaluate the result.
9231 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9232 << Alignment;
9233 return false;
9234 }
9235 case Builtin::BI__builtin_operator_new:
9236 return HandleOperatorNewCall(Info, E, Result);
9237 case Builtin::BI__builtin_launder:
9238 return evaluatePointer(E->getArg(0), Result);
9239 case Builtin::BIstrchr:
9240 case Builtin::BIwcschr:
9241 case Builtin::BImemchr:
9242 case Builtin::BIwmemchr:
9243 if (Info.getLangOpts().CPlusPlus11)
9244 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9245 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9246 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9247 else
9248 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9249 [[fallthrough]];
9250 case Builtin::BI__builtin_strchr:
9251 case Builtin::BI__builtin_wcschr:
9252 case Builtin::BI__builtin_memchr:
9253 case Builtin::BI__builtin_char_memchr:
9254 case Builtin::BI__builtin_wmemchr: {
9255 if (!Visit(E->getArg(0)))
9256 return false;
9257 APSInt Desired;
9258 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9259 return false;
9260 uint64_t MaxLength = uint64_t(-1);
9261 if (BuiltinOp != Builtin::BIstrchr &&
9262 BuiltinOp != Builtin::BIwcschr &&
9263 BuiltinOp != Builtin::BI__builtin_strchr &&
9264 BuiltinOp != Builtin::BI__builtin_wcschr) {
9265 APSInt N;
9266 if (!EvaluateInteger(E->getArg(2), N, Info))
9267 return false;
9268 MaxLength = N.getExtValue();
9269 }
9270 // We cannot find the value if there are no candidates to match against.
9271 if (MaxLength == 0u)
9272 return ZeroInitialization(E);
9273 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9274 Result.Designator.Invalid)
9275 return false;
9276 QualType CharTy = Result.Designator.getType(Info.Ctx);
9277 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9278 BuiltinOp == Builtin::BI__builtin_memchr;
9279 assert(IsRawByte ||(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType
( CharTy, E->getArg(0)->getType()->getPointeeType())
) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/AST/ExprConstant.cpp", 9281, __extension__ __PRETTY_FUNCTION__
))
9280 Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType
( CharTy, E->getArg(0)->getType()->getPointeeType())
) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/AST/ExprConstant.cpp", 9281, __extension__ __PRETTY_FUNCTION__
))
9281 CharTy, E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType
( CharTy, E->getArg(0)->getType()->getPointeeType())
) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/AST/ExprConstant.cpp", 9281, __extension__ __PRETTY_FUNCTION__
))
;
9282 // Pointers to const void may point to objects of incomplete type.
9283 if (IsRawByte && CharTy->isIncompleteType()) {
9284 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9285 return false;
9286 }
9287 // Give up on byte-oriented matching against multibyte elements.
9288 // FIXME: We can compare the bytes in the correct order.
9289 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9290 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9291 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9292 << CharTy;
9293 return false;
9294 }
9295 // Figure out what value we're actually looking for (after converting to
9296 // the corresponding unsigned type if necessary).
9297 uint64_t DesiredVal;
9298 bool StopAtNull = false;
9299 switch (BuiltinOp) {
9300 case Builtin::BIstrchr:
9301 case Builtin::BI__builtin_strchr:
9302 // strchr compares directly to the passed integer, and therefore
9303 // always fails if given an int that is not a char.
9304 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9305 E->getArg(1)->getType(),
9306 Desired),
9307 Desired))
9308 return ZeroInitialization(E);
9309 StopAtNull = true;
9310 [[fallthrough]];
9311 case Builtin::BImemchr:
9312 case Builtin::BI__builtin_memchr:
9313 case Builtin::BI__builtin_char_memchr:
9314 // memchr compares by converting both sides to unsigned char. That's also
9315 // correct for strchr if we get this far (to cope with plain char being
9316 // unsigned in the strchr case).
9317 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9318 break;
9319
9320 case Builtin::BIwcschr:
9321 case Builtin::BI__builtin_wcschr:
9322 StopAtNull = true;
9323 [[fallthrough]];
9324 case Builtin::BIwmemchr:
9325 case Builtin::BI__builtin_wmemchr:
9326 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9327 DesiredVal = Desired.getZExtValue();
9328 break;
9329 }
9330
9331 for (; MaxLength; --MaxLength) {
9332 APValue Char;
9333 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9334 !Char.isInt())
9335 return false;
9336 if (Char.getInt().getZExtValue() == DesiredVal)
9337 return true;
9338 if (StopAtNull && !Char.getInt())
9339 break;
9340 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9341 return false;
9342 }
9343 // Not found: return nullptr.
9344 return ZeroInitialization(E);
9345 }
9346
9347 case Builtin::BImemcpy:
9348 case Builtin::BImemmove:
9349 case Builtin::BIwmemcpy:
9350 case Builtin::BIwmemmove:
9351 if (Info.getLangOpts().CPlusPlus11)
9352 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9353 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9354 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9355 else
9356 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9357 [[fallthrough]];
9358 case Builtin::BI__builtin_memcpy:
9359 case Builtin::BI__builtin_memmove:
9360 case Builtin::BI__builtin_wmemcpy:
9361 case Builtin::BI__builtin_wmemmove: {
9362 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9363 BuiltinOp == Builtin::BIwmemmove ||
9364 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9365 BuiltinOp == Builtin::BI__builtin_wmemmove;
9366 bool Move = BuiltinOp == Builtin::BImemmove ||
9367 BuiltinOp == Builtin::BIwmemmove ||
9368 BuiltinOp == Builtin::BI__builtin_memmove ||
9369 BuiltinOp == Builtin::BI__builtin_wmemmove;
9370
9371 // The result of mem* is the first argument.
9372 if (!Visit(E->getArg(0)))
9373 return false;
9374 LValue Dest = Result;
9375
9376 LValue Src;
9377 if (!EvaluatePointer(E->getArg(1), Src, Info))
9378 return false;
9379
9380 APSInt N;
9381 if (!EvaluateInteger(E->getArg(2), N, Info))
9382 return false;
9383 assert(!N.isSigned() && "memcpy and friends take an unsigned size")(static_cast <bool> (!N.isSigned() && "memcpy and friends take an unsigned size"
) ? void (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\""
, "clang/lib/AST/ExprConstant.cpp", 9383, __extension__ __PRETTY_FUNCTION__
))
;
9384
9385 // If the size is zero, we treat this as always being a valid no-op.
9386 // (Even if one of the src and dest pointers is null.)
9387 if (!N)
9388 return true;
9389
9390 // Otherwise, if either of the operands is null, we can't proceed. Don't
9391 // try to determine the type of the copied objects, because there aren't
9392 // any.
9393 if (!Src.Base || !Dest.Base) {
9394 APValue Val;
9395 (!Src.Base ? Src : Dest).moveInto(Val);
9396 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9397 << Move << WChar << !!Src.Base
9398 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9399 return false;
9400 }
9401 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9402 return false;
9403
9404 // We require that Src and Dest are both pointers to arrays of
9405 // trivially-copyable type. (For the wide version, the designator will be
9406 // invalid if the designated object is not a wchar_t.)
9407 QualType T = Dest.Designator.getType(Info.Ctx);
9408 QualType SrcT = Src.Designator.getType(Info.Ctx);
9409 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9410 // FIXME: Consider using our bit_cast implementation to support this.
9411 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9412 return false;
9413 }
9414 if (T->isIncompleteType()) {
9415 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9416 return false;
9417 }
9418 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9419 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9420 return false;
9421 }
9422
9423 // Figure out how many T's we're copying.
9424 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9425 if (!WChar) {
9426 uint64_t Remainder;
9427 llvm::APInt OrigN = N;
9428 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9429 if (Remainder) {
9430 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9431 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9432 << (unsigned)TSize;
9433 return false;
9434 }
9435 }
9436
9437 // Check that the copying will remain within the arrays, just so that we
9438 // can give a more meaningful diagnostic. This implicitly also checks that
9439 // N fits into 64 bits.
9440 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9441 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9442 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9443 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9444 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9445 << toString(N, 10, /*Signed*/false);
9446 return false;
9447 }
9448 uint64_t NElems = N.getZExtValue();
9449 uint64_t NBytes = NElems * TSize;
9450
9451 // Check for overlap.
9452 int Direction = 1;
9453 if (HasSameBase(Src, Dest)) {
9454 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9455 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9456 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9457 // Dest is inside the source region.
9458 if (!Move) {
9459 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9460 return false;
9461 }
9462 // For memmove and friends, copy backwards.
9463 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9464 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9465 return false;
9466 Direction = -1;
9467 } else if (!Move && SrcOffset >= DestOffset &&
9468 SrcOffset - DestOffset < NBytes) {
9469 // Src is inside the destination region for memcpy: invalid.
9470 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9471 return false;
9472 }
9473 }
9474
9475 while (true) {
9476 APValue Val;
9477 // FIXME: Set WantObjectRepresentation to true if we're copying a
9478 // char-like type?
9479 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9480 !handleAssignment(Info, E, Dest, T, Val))
9481 return false;
9482 // Do not iterate past the last element; if we're copying backwards, that
9483 // might take us off the start of the array.
9484 if (--NElems == 0)
9485 return true;
9486 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9487 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9488 return false;
9489 }
9490 }
9491
9492 default:
9493 return false;
9494 }
9495}
9496
9497static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9498 APValue &Result, const InitListExpr *ILE,
9499 QualType AllocType);
9500static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9501 APValue &Result,
9502 const CXXConstructExpr *CCE,
9503 QualType AllocType);
9504
9505bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9506 if (!Info.getLangOpts().CPlusPlus20)
9507 Info.CCEDiag(E, diag::note_constexpr_new);
9508
9509 // We cannot speculatively evaluate a delete expression.
9510 if (Info.SpeculativeEvaluationDepth)
9511 return false;
9512
9513 FunctionDecl *OperatorNew = E->getOperatorNew();
9514
9515 bool IsNothrow = false;
9516 bool IsPlacement = false;
9517 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9518 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9519 // FIXME Support array placement new.
9520 assert(E->getNumPlacementArgs() == 1)(static_cast <bool> (E->getNumPlacementArgs() == 1) ?
void (0) : __assert_fail ("E->getNumPlacementArgs() == 1"
, "clang/lib/AST/ExprConstant.cpp", 9520, __extension__ __PRETTY_FUNCTION__
))
;
9521 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9522 return false;
9523 if (Result.Designator.Invalid)
9524 return false;
9525 IsPlacement = true;
9526 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9527 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9528 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9529 return false;
9530 } else if (E->getNumPlacementArgs()) {
9531 // The only new-placement list we support is of the form (std::nothrow).
9532 //
9533 // FIXME: There is no restriction on this, but it's not clear that any
9534 // other form makes any sense. We get here for cases such as:
9535 //
9536 // new (std::align_val_t{N}) X(int)
9537 //
9538 // (which should presumably be valid only if N is a multiple of
9539 // alignof(int), and in any case can't be deallocated unless N is
9540 // alignof(X) and X has new-extended alignment).
9541 if (E->getNumPlacementArgs() != 1 ||
9542 !E->getPlacementArg(0)->getType()->isNothrowT())
9543 return Error(E, diag::note_constexpr_new_placement);
9544
9545 LValue Nothrow;
9546 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9547 return false;
9548 IsNothrow = true;
9549 }
9550
9551 const Expr *Init = E->getInitializer();
9552 const InitListExpr *ResizedArrayILE = nullptr;
9553 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9554 bool ValueInit = false;
9555
9556 QualType AllocType = E->getAllocatedType();
9557 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9558 const Expr *Stripped = *ArraySize;
9559 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9560 Stripped = ICE->getSubExpr())
9561 if (ICE->getCastKind() != CK_NoOp &&
9562 ICE->getCastKind() != CK_IntegralCast)
9563 break;
9564
9565 llvm::APSInt ArrayBound;
9566 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9567 return false;
9568
9569 // C++ [expr.new]p9:
9570 // The expression is erroneous if:
9571 // -- [...] its value before converting to size_t [or] applying the
9572 // second standard conversion sequence is less than zero
9573 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9574 if (IsNothrow)
9575 return ZeroInitialization(E);
9576
9577 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9578 << ArrayBound << (*ArraySize)->getSourceRange();
9579 return false;
9580 }
9581
9582 // -- its value is such that the size of the allocated object would
9583 // exceed the implementation-defined limit
9584 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9585 ArrayBound) >
9586 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9587 if (IsNothrow)
9588 return ZeroInitialization(E);
9589
9590 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9591 << ArrayBound << (*ArraySize)->getSourceRange();
9592 return false;
9593 }
9594
9595 // -- the new-initializer is a braced-init-list and the number of
9596 // array elements for which initializers are provided [...]
9597 // exceeds the number of elements to initialize
9598 if (!Init) {
9599 // No initialization is performed.
9600 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9601 isa<ImplicitValueInitExpr>(Init)) {
9602 ValueInit = true;
9603 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9604 ResizedArrayCCE = CCE;
9605 } else {
9606 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9607 assert(CAT && "unexpected type for array initializer")(static_cast <bool> (CAT && "unexpected type for array initializer"
) ? void (0) : __assert_fail ("CAT && \"unexpected type for array initializer\""
, "clang/lib/AST/ExprConstant.cpp", 9607, __extension__ __PRETTY_FUNCTION__
))
;
9608
9609 unsigned Bits =
9610 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9611 llvm::APInt InitBound = CAT->getSize().zext(Bits);
9612 llvm::APInt AllocBound = ArrayBound.zext(Bits);
9613 if (InitBound.ugt(AllocBound)) {
9614 if (IsNothrow)
9615 return ZeroInitialization(E);
9616
9617 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9618 << toString(AllocBound, 10, /*Signed=*/false)
9619 << toString(InitBound, 10, /*Signed=*/false)
9620 << (*ArraySize)->getSourceRange();
9621 return false;
9622 }
9623
9624 // If the sizes differ, we must have an initializer list, and we need
9625 // special handling for this case when we initialize.
9626 if (InitBound != AllocBound)
9627 ResizedArrayILE = cast<InitListExpr>(Init);
9628 }
9629
9630 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9631 ArrayType::Normal, 0);
9632 } else {
9633 assert(!AllocType->isArrayType() &&(static_cast <bool> (!AllocType->isArrayType() &&
"array allocation with non-array new") ? void (0) : __assert_fail
("!AllocType->isArrayType() && \"array allocation with non-array new\""
, "clang/lib/AST/ExprConstant.cpp", 9634, __extension__ __PRETTY_FUNCTION__
))
9634 "array allocation with non-array new")(static_cast <bool> (!AllocType->isArrayType() &&
"array allocation with non-array new") ? void (0) : __assert_fail
("!AllocType->isArrayType() && \"array allocation with non-array new\""
, "clang/lib/AST/ExprConstant.cpp", 9634, __extension__ __PRETTY_FUNCTION__
))
;
9635 }
9636
9637 APValue *Val;
9638 if (IsPlacement) {
9639 AccessKinds AK = AK_Construct;
9640 struct FindObjectHandler {
9641 EvalInfo &Info;
9642 const Expr *E;
9643 QualType AllocType;
9644 const AccessKinds AccessKind;
9645 APValue *Value;
9646
9647 typedef bool result_type;
9648 bool failed() { return false; }
9649 bool found(APValue &Subobj, QualType SubobjType) {
9650 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9651 // old name of the object to be used to name the new object.
9652 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9653 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9654 SubobjType << AllocType;
9655 return false;
9656 }
9657 Value = &Subobj;
9658 return true;
9659 }
9660 bool found(APSInt &Value, QualType SubobjType) {
9661 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9662 return false;
9663 }
9664 bool found(APFloat &Value, QualType SubobjType) {
9665 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9666 return false;
9667 }
9668 } Handler = {Info, E, AllocType, AK, nullptr};
9669
9670 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9671 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9672 return false;
9673
9674 Val = Handler.Value;
9675
9676 // [basic.life]p1:
9677 // The lifetime of an object o of type T ends when [...] the storage
9678 // which the object occupies is [...] reused by an object that is not
9679 // nested within o (6.6.2).
9680 *Val = APValue();
9681 } else {
9682 // Perform the allocation and obtain a pointer to the resulting object.
9683 Val = Info.createHeapAlloc(E, AllocType, Result);
9684 if (!Val)
9685 return false;
9686 }
9687
9688 if (ValueInit) {
9689 ImplicitValueInitExpr VIE(AllocType);
9690 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9691 return false;
9692 } else if (ResizedArrayILE) {
9693 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9694 AllocType))
9695 return false;
9696 } else if (ResizedArrayCCE) {
9697 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9698 AllocType))
9699 return false;
9700 } else if (Init) {
9701 if (!EvaluateInPlace(*Val, Info, Result, Init))
9702 return false;
9703 } else if (!getDefaultInitValue(AllocType, *Val)) {
9704 return false;
9705 }
9706
9707 // Array new returns a pointer to the first element, not a pointer to the
9708 // array.
9709 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9710 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9711
9712 return true;
9713}
9714//===----------------------------------------------------------------------===//
9715// Member Pointer Evaluation
9716//===----------------------------------------------------------------------===//
9717
9718namespace {
9719class MemberPointerExprEvaluator
9720 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9721 MemberPtr &Result;
9722
9723 bool Success(const ValueDecl *D) {
9724 Result = MemberPtr(D);
9725 return true;
9726 }
9727public:
9728
9729 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9730 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9731
9732 bool Success(const APValue &V, const Expr *E) {
9733 Result.setFrom(V);
9734 return true;
9735 }
9736 bool ZeroInitialization(const Expr *E) {
9737 return Success((const ValueDecl*)nullptr);
9738 }
9739
9740 bool VisitCastExpr(const CastExpr *E);
9741 bool VisitUnaryAddrOf(const UnaryOperator *E);
9742};
9743} // end anonymous namespace
9744
9745static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9746 EvalInfo &Info) {
9747 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 9747, __extension__ __PRETTY_FUNCTION__))
;
9748 assert(E->isPRValue() && E->getType()->isMemberPointerType())(static_cast <bool> (E->isPRValue() && E->
getType()->isMemberPointerType()) ? void (0) : __assert_fail
("E->isPRValue() && E->getType()->isMemberPointerType()"
, "clang/lib/AST/ExprConstant.cpp", 9748, __extension__ __PRETTY_FUNCTION__
))
;
9749 return MemberPointerExprEvaluator(Info, Result).Visit(E);
9750}
9751
9752bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9753 switch (E->getCastKind()) {
9754 default:
9755 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9756
9757 case CK_NullToMemberPointer:
9758 VisitIgnoredValue(E->getSubExpr());
9759 return ZeroInitialization(E);
9760
9761 case CK_BaseToDerivedMemberPointer: {
9762 if (!Visit(E->getSubExpr()))
9763 return false;
9764 if (E->path_empty())
9765 return true;
9766 // Base-to-derived member pointer casts store the path in derived-to-base
9767 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9768 // the wrong end of the derived->base arc, so stagger the path by one class.
9769 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9770 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9771 PathI != PathE; ++PathI) {
9772 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() &&
"memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "clang/lib/AST/ExprConstant.cpp", 9772, __extension__ __PRETTY_FUNCTION__
))
;
9773 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9774 if (!Result.castToDerived(Derived))
9775 return Error(E);
9776 }
9777 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9778 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9779 return Error(E);
9780 return true;
9781 }
9782
9783 case CK_DerivedToBaseMemberPointer:
9784 if (!Visit(E->getSubExpr()))
9785 return false;
9786 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9787 PathE = E->path_end(); PathI != PathE; ++PathI) {
9788 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() &&
"memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "clang/lib/AST/ExprConstant.cpp", 9788, __extension__ __PRETTY_FUNCTION__
))
;
9789 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9790 if (!Result.castToBase(Base))
9791 return Error(E);
9792 }
9793 return true;
9794 }
9795}
9796
9797bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9798 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9799 // member can be formed.
9800 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9801}
9802
9803//===----------------------------------------------------------------------===//
9804// Record Evaluation
9805//===----------------------------------------------------------------------===//
9806
9807namespace {
9808 class RecordExprEvaluator
9809 : public ExprEvaluatorBase<RecordExprEvaluator> {
9810 const LValue &This;
9811 APValue &Result;
9812 public:
9813
9814 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9815 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9816
9817 bool Success(const APValue &V, const Expr *E) {
9818 Result = V;
9819 return true;
9820 }
9821 bool ZeroInitialization(const Expr *E) {
9822 return ZeroInitialization(E, E->getType());
9823 }
9824 bool ZeroInitialization(const Expr *E, QualType T);
9825
9826 bool VisitCallExpr(const CallExpr *E) {
9827 return handleCallExpr(E, Result, &This);
9828 }
9829 bool VisitCastExpr(const CastExpr *E);
9830 bool VisitInitListExpr(const InitListExpr *E);
9831 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9832 return VisitCXXConstructExpr(E, E->getType());
9833 }
9834 bool VisitLambdaExpr(const LambdaExpr *E);
9835 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9836 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9837 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9838 bool VisitBinCmp(const BinaryOperator *E);
9839 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
9840 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
9841 ArrayRef<Expr *> Args);
9842 };
9843}
9844
9845/// Perform zero-initialization on an object of non-union class type.
9846/// C++11 [dcl.init]p5:
9847/// To zero-initialize an object or reference of type T means:
9848/// [...]
9849/// -- if T is a (possibly cv-qualified) non-union class type,
9850/// each non-static data member and each base-class subobject is
9851/// zero-initialized
9852static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9853 const RecordDecl *RD,
9854 const LValue &This, APValue &Result) {
9855 assert(!RD->isUnion() && "Expected non-union class type")(static_cast <bool> (!RD->isUnion() && "Expected non-union class type"
) ? void (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\""
, "clang/lib/AST/ExprConstant.cpp", 9855, __extension__ __PRETTY_FUNCTION__
))
;
9856 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9857 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9858 std::distance(RD->field_begin(), RD->field_end()));
9859
9860 if (RD->isInvalidDecl()) return false;
9861 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9862
9863 if (CD) {
9864 unsigned Index = 0;
9865 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9866 End = CD->bases_end(); I != End; ++I, ++Index) {
9867 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9868 LValue Subobject = This;
9869 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9870 return false;
9871 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9872 Result.getStructBase(Index)))
9873 return false;
9874 }
9875 }
9876
9877 for (const auto *I : RD->fields()) {
9878 // -- if T is a reference type, no initialization is performed.
9879 if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9880 continue;
9881
9882 LValue Subobject = This;
9883 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9884 return false;
9885
9886 ImplicitValueInitExpr VIE(I->getType());
9887 if (!EvaluateInPlace(
9888 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9889 return false;
9890 }
9891
9892 return true;
9893}
9894
9895bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9896 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9897 if (RD->isInvalidDecl()) return false;
9898 if (RD->isUnion()) {
9899 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9900 // object's first non-static named data member is zero-initialized
9901 RecordDecl::field_iterator I = RD->field_begin();
9902 while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9903 ++I;
9904 if (I == RD->field_end()) {
9905 Result = APValue((const FieldDecl*)nullptr);
9906 return true;
9907 }
9908
9909 LValue Subobject = This;
9910 if (!HandleLValueMember(Info, E, Subobject, *I))
9911 return false;
9912 Result = APValue(*I);
9913 ImplicitValueInitExpr VIE(I->getType());
9914 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9915 }
9916
9917 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9918 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9919 return false;
9920 }
9921
9922 return HandleClassZeroInitialization(Info, E, RD, This, Result);
9923}
9924
9925bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9926 switch (E->getCastKind()) {
9927 default:
9928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9929
9930 case CK_ConstructorConversion:
9931 return Visit(E->getSubExpr());
9932
9933 case CK_DerivedToBase:
9934 case CK_UncheckedDerivedToBase: {
9935 APValue DerivedObject;
9936 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9937 return false;
9938 if (!DerivedObject.isStruct())
9939 return Error(E->getSubExpr());
9940
9941 // Derived-to-base rvalue conversion: just slice off the derived part.
9942 APValue *Value = &DerivedObject;
9943 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9944 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9945 PathE = E->path_end(); PathI != PathE; ++PathI) {
9946 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")(static_cast <bool> (!(*PathI)->isVirtual() &&
"record rvalue with virtual base") ? void (0) : __assert_fail
("!(*PathI)->isVirtual() && \"record rvalue with virtual base\""
, "clang/lib/AST/ExprConstant.cpp", 9946, __extension__ __PRETTY_FUNCTION__
))
;
9947 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9948 Value = &Value->getStructBase(getBaseIndex(RD, Base));
9949 RD = Base;
9950 }
9951 Result = *Value;
9952 return true;
9953 }
9954 }
9955}
9956
9957bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9958 if (E->isTransparent())
9959 return Visit(E->getInit(0));
9960 return VisitCXXParenListOrInitListExpr(E, E->inits());
9961}
9962
9963bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
9964 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
9965 const RecordDecl *RD =
9966 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
9967 if (RD->isInvalidDecl()) return false;
9968 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9969 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9970
9971 EvalInfo::EvaluatingConstructorRAII EvalObj(
9972 Info,
9973 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9974 CXXRD && CXXRD->getNumBases());
9975
9976 if (RD->isUnion()) {
9977 const FieldDecl *Field;
9978 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
9979 Field = ILE->getInitializedFieldInUnion();
9980 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
9981 Field = PLIE->getInitializedFieldInUnion();
9982 } else {
9983 llvm_unreachable(::llvm::llvm_unreachable_internal("Expression is neither an init list nor a C++ paren list"
, "clang/lib/AST/ExprConstant.cpp", 9984)
9984 "Expression is neither an init list nor a C++ paren list")::llvm::llvm_unreachable_internal("Expression is neither an init list nor a C++ paren list"
, "clang/lib/AST/ExprConstant.cpp", 9984)
;
9985 }
9986
9987 Result = APValue(Field);
9988 if (!Field)
9989 return true;
9990
9991 // If the initializer list for a union does not contain any elements, the
9992 // first element of the union is value-initialized.
9993 // FIXME: The element should be initialized from an initializer list.
9994 // Is this difference ever observable for initializer lists which
9995 // we don't build?
9996 ImplicitValueInitExpr VIE(Field->getType());
9997 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
9998
9999 LValue Subobject = This;
10000 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10001 return false;
10002
10003 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10004 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10005 isa<CXXDefaultInitExpr>(InitExpr));
10006
10007 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10008 if (Field->isBitField())
10009 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10010 Field);
10011 return true;
10012 }
10013
10014 return false;
10015 }
10016
10017 if (!Result.hasValue())
10018 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10019 std::distance(RD->field_begin(), RD->field_end()));
10020 unsigned ElementNo = 0;
10021 bool Success = true;
10022
10023 // Initialize base classes.
10024 if (CXXRD && CXXRD->getNumBases()) {
10025 for (const auto &Base : CXXRD->bases()) {
10026 assert(ElementNo < Args.size() && "missing init for base class")(static_cast <bool> (ElementNo < Args.size() &&
"missing init for base class") ? void (0) : __assert_fail ("ElementNo < Args.size() && \"missing init for base class\""
, "clang/lib/AST/ExprConstant.cpp", 10026, __extension__ __PRETTY_FUNCTION__
))
;
10027 const Expr *Init = Args[ElementNo];
10028
10029 LValue Subobject = This;
10030 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10031 return false;
10032
10033 APValue &FieldVal = Result.getStructBase(ElementNo);
10034 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10035 if (!Info.noteFailure())
10036 return false;
10037 Success = false;
10038 }
10039 ++ElementNo;
10040 }
10041
10042 EvalObj.finishedConstructingBases();
10043 }
10044
10045 // Initialize members.
10046 for (const auto *Field : RD->fields()) {
10047 // Anonymous bit-fields are not considered members of the class for
10048 // purposes of aggregate initialization.
10049 if (Field->isUnnamedBitfield())
10050 continue;
10051
10052 LValue Subobject = This;
10053
10054 bool HaveInit = ElementNo < Args.size();
10055
10056 // FIXME: Diagnostics here should point to the end of the initializer
10057 // list, not the start.
10058 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10059 Subobject, Field, &Layout))
10060 return false;
10061
10062 // Perform an implicit value-initialization for members beyond the end of
10063 // the initializer list.
10064 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10065 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10066
10067 if (Field->getType()->isIncompleteArrayType()) {
10068 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10069 if (!CAT->getSize().isZero()) {
10070 // Bail out for now. This might sort of "work", but the rest of the
10071 // code isn't really prepared to handle it.
10072 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10073 return false;
10074 }
10075 }
10076 }
10077
10078 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10079 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10080 isa<CXXDefaultInitExpr>(Init));
10081
10082 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10083 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10084 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10085 FieldVal, Field))) {
10086 if (!Info.noteFailure())
10087 return false;
10088 Success = false;
10089 }
10090 }
10091
10092 EvalObj.finishedConstructingFields();
10093
10094 return Success;
10095}
10096
10097bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10098 QualType T) {
10099 // Note that E's type is not necessarily the type of our class here; we might
10100 // be initializing an array element instead.
10101 const CXXConstructorDecl *FD = E->getConstructor();
10102 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10103
10104 bool ZeroInit = E->requiresZeroInitialization();
10105 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10106 // If we've already performed zero-initialization, we're already done.
10107 if (Result.hasValue())
10108 return true;
10109
10110 if (ZeroInit)
10111 return ZeroInitialization(E, T);
10112
10113 return getDefaultInitValue(T, Result);
10114 }
10115
10116 const FunctionDecl *Definition = nullptr;
10117 auto Body = FD->getBody(Definition);
10118
10119 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10120 return false;
10121
10122 // Avoid materializing a temporary for an elidable copy/move constructor.
10123 if (E->isElidable() && !ZeroInit) {
10124 // FIXME: This only handles the simplest case, where the source object
10125 // is passed directly as the first argument to the constructor.
10126 // This should also handle stepping though implicit casts and
10127 // and conversion sequences which involve two steps, with a
10128 // conversion operator followed by a converting constructor.
10129 const Expr *SrcObj = E->getArg(0);
10130 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()))(static_cast <bool> (SrcObj->isTemporaryObject(Info.
Ctx, FD->getParent())) ? void (0) : __assert_fail ("SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())"
, "clang/lib/AST/ExprConstant.cpp", 10130, __extension__ __PRETTY_FUNCTION__
))
;
10131 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()))(static_cast <bool> (Info.Ctx.hasSameUnqualifiedType(E->
getType(), SrcObj->getType())) ? void (0) : __assert_fail (
"Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())"
, "clang/lib/AST/ExprConstant.cpp", 10131, __extension__ __PRETTY_FUNCTION__
))
;
10132 if (const MaterializeTemporaryExpr *ME =
10133 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10134 return Visit(ME->getSubExpr());
10135 }
10136
10137 if (ZeroInit && !ZeroInitialization(E, T))
10138 return false;
10139
10140 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10141 return HandleConstructorCall(E, This, Args,
10142 cast<CXXConstructorDecl>(Definition), Info,
10143 Result);
10144}
10145
10146bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10147 const CXXInheritedCtorInitExpr *E) {
10148 if (!Info.CurrentCall) {
10149 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "clang/lib/AST/ExprConstant.cpp", 10149, __extension__ __PRETTY_FUNCTION__
))
;
10150 return false;
10151 }
10152
10153 const CXXConstructorDecl *FD = E->getConstructor();
10154 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10155 return false;
10156
10157 const FunctionDecl *Definition = nullptr;
10158 auto Body = FD->getBody(Definition);
10159
10160 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10161 return false;
10162
10163 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10164 cast<CXXConstructorDecl>(Definition), Info,
10165 Result);
10166}
10167
10168bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10169 const CXXStdInitializerListExpr *E) {
10170 const ConstantArrayType *ArrayType =
10171 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10172
10173 LValue Array;
10174 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10175 return false;
10176
10177 // Get a pointer to the first element of the array.
10178 Array.addArray(Info, E, ArrayType);
10179
10180 auto InvalidType = [&] {
10181 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10182 << E->getType();
10183 return false;
10184 };
10185
10186 // FIXME: Perform the checks on the field types in SemaInit.
10187 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10188 RecordDecl::field_iterator Field = Record->field_begin();
10189 if (Field == Record->field_end())
10190 return InvalidType();
10191
10192 // Start pointer.
10193 if (!Field->getType()->isPointerType() ||
10194 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10195 ArrayType->getElementType()))
10196 return InvalidType();
10197
10198 // FIXME: What if the initializer_list type has base classes, etc?
10199 Result = APValue(APValue::UninitStruct(), 0, 2);
10200 Array.moveInto(Result.getStructField(0));
10201
10202 if (++Field == Record->field_end())
10203 return InvalidType();
10204
10205 if (Field->getType()->isPointerType() &&
10206 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10207 ArrayType->getElementType())) {
10208 // End pointer.
10209 if (!HandleLValueArrayAdjustment(Info, E, Array,
10210 ArrayType->getElementType(),
10211 ArrayType->getSize().getZExtValue()))
10212 return false;
10213 Array.moveInto(Result.getStructField(1));
10214 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10215 // Length.
10216 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10217 else
10218 return InvalidType();
10219
10220 if (++Field != Record->field_end())
10221 return InvalidType();
10222
10223 return true;
10224}
10225
10226bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10227 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10228 if (ClosureClass->isInvalidDecl())
10229 return false;
10230
10231 const size_t NumFields =
10232 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10233
10234 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "clang/lib/AST/ExprConstant.cpp", 10237, __extension__ __PRETTY_FUNCTION__
))
10235 E->capture_init_end()) &&(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "clang/lib/AST/ExprConstant.cpp", 10237, __extension__ __PRETTY_FUNCTION__
))
10236 "The number of lambda capture initializers should equal the number of "(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "clang/lib/AST/ExprConstant.cpp", 10237, __extension__ __PRETTY_FUNCTION__
))
10237 "fields within the closure type")(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "clang/lib/AST/ExprConstant.cpp", 10237, __extension__ __PRETTY_FUNCTION__
))
;
10238
10239 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10240 // Iterate through all the lambda's closure object's fields and initialize
10241 // them.
10242 auto *CaptureInitIt = E->capture_init_begin();
10243 bool Success = true;
10244 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10245 for (const auto *Field : ClosureClass->fields()) {
10246 assert(CaptureInitIt != E->capture_init_end())(static_cast <bool> (CaptureInitIt != E->capture_init_end
()) ? void (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()"
, "clang/lib/AST/ExprConstant.cpp", 10246, __extension__ __PRETTY_FUNCTION__
))
;
10247 // Get the initializer for this field
10248 Expr *const CurFieldInit = *CaptureInitIt++;
10249
10250 // If there is no initializer, either this is a VLA or an error has
10251 // occurred.
10252 if (!CurFieldInit)
10253 return Error(E);
10254
10255 LValue Subobject = This;
10256
10257 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10258 return false;
10259
10260 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10261 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10262 if (!Info.keepEvaluatingAfterFailure())
10263 return false;
10264 Success = false;
10265 }
10266 }
10267 return Success;
10268}
10269
10270static bool EvaluateRecord(const Expr *E, const LValue &This,
10271 APValue &Result, EvalInfo &Info) {
10272 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10272, __extension__ __PRETTY_FUNCTION__))
;
10273 assert(E->isPRValue() && E->getType()->isRecordType() &&(static_cast <bool> (E->isPRValue() && E->
getType()->isRecordType() && "can't evaluate expression as a record rvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10274, __extension__ __PRETTY_FUNCTION__
))
10274 "can't evaluate expression as a record rvalue")(static_cast <bool> (E->isPRValue() && E->
getType()->isRecordType() && "can't evaluate expression as a record rvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10274, __extension__ __PRETTY_FUNCTION__
))
;
10275 return RecordExprEvaluator(Info, This, Result).Visit(E);
10276}
10277
10278//===----------------------------------------------------------------------===//
10279// Temporary Evaluation
10280//
10281// Temporaries are represented in the AST as rvalues, but generally behave like
10282// lvalues. The full-object of which the temporary is a subobject is implicitly
10283// materialized so that a reference can bind to it.
10284//===----------------------------------------------------------------------===//
10285namespace {
10286class TemporaryExprEvaluator
10287 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10288public:
10289 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10290 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10291
10292 /// Visit an expression which constructs the value of this temporary.
10293 bool VisitConstructExpr(const Expr *E) {
10294 APValue &Value = Info.CurrentCall->createTemporary(
10295 E, E->getType(), ScopeKind::FullExpression, Result);
10296 return EvaluateInPlace(Value, Info, Result, E);
10297 }
10298
10299 bool VisitCastExpr(const CastExpr *E) {
10300 switch (E->getCastKind()) {
10301 default:
10302 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10303
10304 case CK_ConstructorConversion:
10305 return VisitConstructExpr(E->getSubExpr());
10306 }
10307 }
10308 bool VisitInitListExpr(const InitListExpr *E) {
10309 return VisitConstructExpr(E);
10310 }
10311 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10312 return VisitConstructExpr(E);
10313 }
10314 bool VisitCallExpr(const CallExpr *E) {
10315 return VisitConstructExpr(E);
10316 }
10317 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10318 return VisitConstructExpr(E);
10319 }
10320 bool VisitLambdaExpr(const LambdaExpr *E) {
10321 return VisitConstructExpr(E);
10322 }
10323};
10324} // end anonymous namespace
10325
10326/// Evaluate an expression of record type as a temporary.
10327static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10328 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10328, __extension__ __PRETTY_FUNCTION__))
;
10329 assert(E->isPRValue() && E->getType()->isRecordType())(static_cast <bool> (E->isPRValue() && E->
getType()->isRecordType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType()"
, "clang/lib/AST/ExprConstant.cpp", 10329, __extension__ __PRETTY_FUNCTION__
))
;
10330 return TemporaryExprEvaluator(Info, Result).Visit(E);
10331}
10332
10333//===----------------------------------------------------------------------===//
10334// Vector Evaluation
10335//===----------------------------------------------------------------------===//
10336
10337namespace {
10338 class VectorExprEvaluator
10339 : public ExprEvaluatorBase<VectorExprEvaluator> {
10340 APValue &Result;
10341 public:
10342
10343 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10344 : ExprEvaluatorBaseTy(info), Result(Result) {}
10345
10346 bool Success(ArrayRef<APValue> V, const Expr *E) {
10347 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())(static_cast <bool> (V.size() == E->getType()->castAs
<VectorType>()->getNumElements()) ? void (0) : __assert_fail
("V.size() == E->getType()->castAs<VectorType>()->getNumElements()"
, "clang/lib/AST/ExprConstant.cpp", 10347, __extension__ __PRETTY_FUNCTION__
))
;
10348 // FIXME: remove this APValue copy.
10349 Result = APValue(V.data(), V.size());
10350 return true;
10351 }
10352 bool Success(const APValue &V, const Expr *E) {
10353 assert(V.isVector())(static_cast <bool> (V.isVector()) ? void (0) : __assert_fail
("V.isVector()", "clang/lib/AST/ExprConstant.cpp", 10353, __extension__
__PRETTY_FUNCTION__))
;
10354 Result = V;
10355 return true;
10356 }
10357 bool ZeroInitialization(const Expr *E);
10358
10359 bool VisitUnaryReal(const UnaryOperator *E)
10360 { return Visit(E->getSubExpr()); }
10361 bool VisitCastExpr(const CastExpr* E);
10362 bool VisitInitListExpr(const InitListExpr *E);
10363 bool VisitUnaryImag(const UnaryOperator *E);
10364 bool VisitBinaryOperator(const BinaryOperator *E);
10365 bool VisitUnaryOperator(const UnaryOperator *E);
10366 // FIXME: Missing: conditional operator (for GNU
10367 // conditional select), shufflevector, ExtVectorElementExpr
10368 };
10369} // end anonymous namespace
10370
10371static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10372 assert(E->isPRValue() && E->getType()->isVectorType() &&(static_cast <bool> (E->isPRValue() && E->
getType()->isVectorType() && "not a vector prvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10373, __extension__ __PRETTY_FUNCTION__
))
10373 "not a vector prvalue")(static_cast <bool> (E->isPRValue() && E->
getType()->isVectorType() && "not a vector prvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10373, __extension__ __PRETTY_FUNCTION__
))
;
10374 return VectorExprEvaluator(Info, Result).Visit(E);
10375}
10376
10377bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10378 const VectorType *VTy = E->getType()->castAs<VectorType>();
10379 unsigned NElts = VTy->getNumElements();
10380
10381 const Expr *SE = E->getSubExpr();
10382 QualType SETy = SE->getType();
10383
10384 switch (E->getCastKind()) {
10385 case CK_VectorSplat: {
10386 APValue Val = APValue();
10387 if (SETy->isIntegerType()) {
10388 APSInt IntResult;
10389 if (!EvaluateInteger(SE, IntResult, Info))
10390 return false;
10391 Val = APValue(std::move(IntResult));
10392 } else if (SETy->isRealFloatingType()) {
10393 APFloat FloatResult(0.0);
10394 if (!EvaluateFloat(SE, FloatResult, Info))
10395 return false;
10396 Val = APValue(std::move(FloatResult));
10397 } else {
10398 return Error(E);
10399 }
10400
10401 // Splat and create vector APValue.
10402 SmallVector<APValue, 4> Elts(NElts, Val);
10403 return Success(Elts, E);
10404 }
10405 case CK_BitCast: {
10406 // Evaluate the operand into an APInt we can extract from.
10407 llvm::APInt SValInt;
10408 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10409 return false;
10410 // Extract the elements
10411 QualType EltTy = VTy->getElementType();
10412 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10413 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10414 SmallVector<APValue, 4> Elts;
10415 if (EltTy->isRealFloatingType()) {
10416 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10417 unsigned FloatEltSize = EltSize;
10418 if (&Sem == &APFloat::x87DoubleExtended())
10419 FloatEltSize = 80;
10420 for (unsigned i = 0; i < NElts; i++) {
10421 llvm::APInt Elt;
10422 if (BigEndian)
10423 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10424 else
10425 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10426 Elts.push_back(APValue(APFloat(Sem, Elt)));
10427 }
10428 } else if (EltTy->isIntegerType()) {
10429 for (unsigned i = 0; i < NElts; i++) {
10430 llvm::APInt Elt;
10431 if (BigEndian)
10432 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10433 else
10434 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10435 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10436 }
10437 } else {
10438 return Error(E);
10439 }
10440 return Success(Elts, E);
10441 }
10442 default:
10443 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10444 }
10445}
10446
10447bool
10448VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10449 const VectorType *VT = E->getType()->castAs<VectorType>();
10450 unsigned NumInits = E->getNumInits();
10451 unsigned NumElements = VT->getNumElements();
10452
10453 QualType EltTy = VT->getElementType();
10454 SmallVector<APValue, 4> Elements;
10455
10456 // The number of initializers can be less than the number of
10457 // vector elements. For OpenCL, this can be due to nested vector
10458 // initialization. For GCC compatibility, missing trailing elements
10459 // should be initialized with zeroes.
10460 unsigned CountInits = 0, CountElts = 0;
10461 while (CountElts < NumElements) {
10462 // Handle nested vector initialization.
10463 if (CountInits < NumInits
10464 && E->getInit(CountInits)->getType()->isVectorType()) {
10465 APValue v;
10466 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10467 return Error(E);
10468 unsigned vlen = v.getVectorLength();
10469 for (unsigned j = 0; j < vlen; j++)
10470 Elements.push_back(v.getVectorElt(j));
10471 CountElts += vlen;
10472 } else if (EltTy->isIntegerType()) {
10473 llvm::APSInt sInt(32);
10474 if (CountInits < NumInits) {
10475 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10476 return false;
10477 } else // trailing integer zero.
10478 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10479 Elements.push_back(APValue(sInt));
10480 CountElts++;
10481 } else {
10482 llvm::APFloat f(0.0);
10483 if (CountInits < NumInits) {
10484 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10485 return false;
10486 } else // trailing float zero.
10487 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10488 Elements.push_back(APValue(f));
10489 CountElts++;
10490 }
10491 CountInits++;
10492 }
10493 return Success(Elements, E);
10494}
10495
10496bool
10497VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10498 const auto *VT = E->getType()->castAs<VectorType>();
10499 QualType EltTy = VT->getElementType();
10500 APValue ZeroElement;
10501 if (EltTy->isIntegerType())
10502 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10503 else
10504 ZeroElement =
10505 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10506
10507 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10508 return Success(Elements, E);
10509}
10510
10511bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10512 VisitIgnoredValue(E->getSubExpr());
10513 return ZeroInitialization(E);
10514}
10515
10516bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10517 BinaryOperatorKind Op = E->getOpcode();
10518 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI
&& Op != BO_Cmp && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 10519, __extension__ __PRETTY_FUNCTION__
))
10519 "Operation not supported on vector types")(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI
&& Op != BO_Cmp && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 10519, __extension__ __PRETTY_FUNCTION__
))
;
10520
10521 if (Op == BO_Comma)
10522 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10523
10524 Expr *LHS = E->getLHS();
10525 Expr *RHS = E->getRHS();
10526
10527 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&(static_cast <bool> (LHS->getType()->isVectorType
() && RHS->getType()->isVectorType() &&
"Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\""
, "clang/lib/AST/ExprConstant.cpp", 10528, __extension__ __PRETTY_FUNCTION__
))
10528 "Must both be vector types")(static_cast <bool> (LHS->getType()->isVectorType
() && RHS->getType()->isVectorType() &&
"Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\""
, "clang/lib/AST/ExprConstant.cpp", 10528, __extension__ __PRETTY_FUNCTION__
))
;
10529 // Checking JUST the types are the same would be fine, except shifts don't
10530 // need to have their types be the same (since you always shift by an int).
10531 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType
>()->getNumElements() == E->getType()->castAs<
VectorType>()->getNumElements() && RHS->getType
()->castAs<VectorType>()->getNumElements() == E->
getType()->castAs<VectorType>()->getNumElements()
&& "All operands must be the same size.") ? void (0)
: __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\""
, "clang/lib/AST/ExprConstant.cpp", 10535, __extension__ __PRETTY_FUNCTION__
))
10532 E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType
>()->getNumElements() == E->getType()->castAs<
VectorType>()->getNumElements() && RHS->getType
()->castAs<VectorType>()->getNumElements() == E->
getType()->castAs<VectorType>()->getNumElements()
&& "All operands must be the same size.") ? void (0)
: __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\""
, "clang/lib/AST/ExprConstant.cpp", 10535, __extension__ __PRETTY_FUNCTION__
))
10533 RHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType
>()->getNumElements() == E->getType()->castAs<
VectorType>()->getNumElements() && RHS->getType
()->castAs<VectorType>()->getNumElements() == E->
getType()->castAs<VectorType>()->getNumElements()
&& "All operands must be the same size.") ? void (0)
: __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\""
, "clang/lib/AST/ExprConstant.cpp", 10535, __extension__ __PRETTY_FUNCTION__
))
10534 E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType
>()->getNumElements() == E->getType()->castAs<
VectorType>()->getNumElements() && RHS->getType
()->castAs<VectorType>()->getNumElements() == E->
getType()->castAs<VectorType>()->getNumElements()
&& "All operands must be the same size.") ? void (0)
: __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\""
, "clang/lib/AST/ExprConstant.cpp", 10535, __extension__ __PRETTY_FUNCTION__
))
10535 "All operands must be the same size.")(static_cast <bool> (LHS->getType()->castAs<VectorType
>()->getNumElements() == E->getType()->castAs<
VectorType>()->getNumElements() && RHS->getType
()->castAs<VectorType>()->getNumElements() == E->
getType()->castAs<VectorType>()->getNumElements()
&& "All operands must be the same size.") ? void (0)
: __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\""
, "clang/lib/AST/ExprConstant.cpp", 10535, __extension__ __PRETTY_FUNCTION__
))
;
10536
10537 APValue LHSValue;
10538 APValue RHSValue;
10539 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10540 if (!LHSOK && !Info.noteFailure())
10541 return false;
10542 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10543 return false;
10544
10545 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10546 return false;
10547
10548 return Success(LHSValue, E);
10549}
10550
10551static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10552 QualType ResultTy,
10553 UnaryOperatorKind Op,
10554 APValue Elt) {
10555 switch (Op) {
10556 case UO_Plus:
10557 // Nothing to do here.
10558 return Elt;
10559 case UO_Minus:
10560 if (Elt.getKind() == APValue::Int) {
10561 Elt.getInt().negate();
10562 } else {
10563 assert(Elt.getKind() == APValue::Float &&(static_cast <bool> (Elt.getKind() == APValue::Float &&
"Vector can only be int or float type") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\""
, "clang/lib/AST/ExprConstant.cpp", 10564, __extension__ __PRETTY_FUNCTION__
))
10564 "Vector can only be int or float type")(static_cast <bool> (Elt.getKind() == APValue::Float &&
"Vector can only be int or float type") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\""
, "clang/lib/AST/ExprConstant.cpp", 10564, __extension__ __PRETTY_FUNCTION__
))
;
10565 Elt.getFloat().changeSign();
10566 }
10567 return Elt;
10568 case UO_Not:
10569 // This is only valid for integral types anyway, so we don't have to handle
10570 // float here.
10571 assert(Elt.getKind() == APValue::Int &&(static_cast <bool> (Elt.getKind() == APValue::Int &&
"Vector operator ~ can only be int") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Int && \"Vector operator ~ can only be int\""
, "clang/lib/AST/ExprConstant.cpp", 10572, __extension__ __PRETTY_FUNCTION__
))
10572 "Vector operator ~ can only be int")(static_cast <bool> (Elt.getKind() == APValue::Int &&
"Vector operator ~ can only be int") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Int && \"Vector operator ~ can only be int\""
, "clang/lib/AST/ExprConstant.cpp", 10572, __extension__ __PRETTY_FUNCTION__
))
;
10573 Elt.getInt().flipAllBits();
10574 return Elt;
10575 case UO_LNot: {
10576 if (Elt.getKind() == APValue::Int) {
10577 Elt.getInt() = !Elt.getInt();
10578 // operator ! on vectors returns -1 for 'truth', so negate it.
10579 Elt.getInt().negate();
10580 return Elt;
10581 }
10582 assert(Elt.getKind() == APValue::Float &&(static_cast <bool> (Elt.getKind() == APValue::Float &&
"Vector can only be int or float type") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\""
, "clang/lib/AST/ExprConstant.cpp", 10583, __extension__ __PRETTY_FUNCTION__
))
10583 "Vector can only be int or float type")(static_cast <bool> (Elt.getKind() == APValue::Float &&
"Vector can only be int or float type") ? void (0) : __assert_fail
("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\""
, "clang/lib/AST/ExprConstant.cpp", 10583, __extension__ __PRETTY_FUNCTION__
))
;
10584 // Float types result in an int of the same size, but -1 for true, or 0 for
10585 // false.
10586 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10587 ResultTy->isUnsignedIntegerType()};
10588 if (Elt.getFloat().isZero())
10589 EltResult.setAllBits();
10590 else
10591 EltResult.clearAllBits();
10592
10593 return APValue{EltResult};
10594 }
10595 default:
10596 // FIXME: Implement the rest of the unary operators.
10597 return std::nullopt;
10598 }
10599}
10600
10601bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10602 Expr *SubExpr = E->getSubExpr();
10603 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10604 // This result element type differs in the case of negating a floating point
10605 // vector, since the result type is the a vector of the equivilant sized
10606 // integer.
10607 const QualType ResultEltTy = VD->getElementType();
10608 UnaryOperatorKind Op = E->getOpcode();
10609
10610 APValue SubExprValue;
10611 if (!Evaluate(SubExprValue, Info, SubExpr))
10612 return false;
10613
10614 // FIXME: This vector evaluator someday needs to be changed to be LValue
10615 // aware/keep LValue information around, rather than dealing with just vector
10616 // types directly. Until then, we cannot handle cases where the operand to
10617 // these unary operators is an LValue. The only case I've been able to see
10618 // cause this is operator++ assigning to a member expression (only valid in
10619 // altivec compilations) in C mode, so this shouldn't limit us too much.
10620 if (SubExprValue.isLValue())
10621 return false;
10622
10623 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&(static_cast <bool> (SubExprValue.getVectorLength() == VD
->getNumElements() && "Vector length doesn't match type?"
) ? void (0) : __assert_fail ("SubExprValue.getVectorLength() == VD->getNumElements() && \"Vector length doesn't match type?\""
, "clang/lib/AST/ExprConstant.cpp", 10624, __extension__ __PRETTY_FUNCTION__
))
10624 "Vector length doesn't match type?")(static_cast <bool> (SubExprValue.getVectorLength() == VD
->getNumElements() && "Vector length doesn't match type?"
) ? void (0) : __assert_fail ("SubExprValue.getVectorLength() == VD->getNumElements() && \"Vector length doesn't match type?\""
, "clang/lib/AST/ExprConstant.cpp", 10624, __extension__ __PRETTY_FUNCTION__
))
;
10625
10626 SmallVector<APValue, 4> ResultElements;
10627 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10628 std::optional<APValue> Elt = handleVectorUnaryOperator(
10629 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10630 if (!Elt)
10631 return false;
10632 ResultElements.push_back(*Elt);
10633 }
10634 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10635}
10636
10637//===----------------------------------------------------------------------===//
10638// Array Evaluation
10639//===----------------------------------------------------------------------===//
10640
10641namespace {
10642 class ArrayExprEvaluator
10643 : public ExprEvaluatorBase<ArrayExprEvaluator> {
10644 const LValue &This;
10645 APValue &Result;
10646 public:
10647
10648 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10649 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10650
10651 bool Success(const APValue &V, const Expr *E) {
10652 assert(V.isArray() && "expected array")(static_cast <bool> (V.isArray() && "expected array"
) ? void (0) : __assert_fail ("V.isArray() && \"expected array\""
, "clang/lib/AST/ExprConstant.cpp", 10652, __extension__ __PRETTY_FUNCTION__
))
;
10653 Result = V;
10654 return true;
10655 }
10656
10657 bool ZeroInitialization(const Expr *E) {
10658 const ConstantArrayType *CAT =
10659 Info.Ctx.getAsConstantArrayType(E->getType());
10660 if (!CAT) {
10661 if (E->getType()->isIncompleteArrayType()) {
10662 // We can be asked to zero-initialize a flexible array member; this
10663 // is represented as an ImplicitValueInitExpr of incomplete array
10664 // type. In this case, the array has zero elements.
10665 Result = APValue(APValue::UninitArray(), 0, 0);
10666 return true;
10667 }
10668 // FIXME: We could handle VLAs here.
10669 return Error(E);
10670 }
10671
10672 Result = APValue(APValue::UninitArray(), 0,
10673 CAT->getSize().getZExtValue());
10674 if (!Result.hasArrayFiller())
10675 return true;
10676
10677 // Zero-initialize all elements.
10678 LValue Subobject = This;
10679 Subobject.addArray(Info, E, CAT);
10680 ImplicitValueInitExpr VIE(CAT->getElementType());
10681 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10682 }
10683
10684 bool VisitCallExpr(const CallExpr *E) {
10685 return handleCallExpr(E, Result, &This);
10686 }
10687 bool VisitInitListExpr(const InitListExpr *E,
10688 QualType AllocType = QualType());
10689 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10690 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10691 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10692 const LValue &Subobject,
10693 APValue *Value, QualType Type);
10694 bool VisitStringLiteral(const StringLiteral *E,
10695 QualType AllocType = QualType()) {
10696 expandStringLiteral(Info, E, Result, AllocType);
10697 return true;
10698 }
10699 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10700 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10701 ArrayRef<Expr *> Args,
10702 const Expr *ArrayFiller,
10703 QualType AllocType = QualType());
10704 };
10705} // end anonymous namespace
10706
10707static bool EvaluateArray(const Expr *E, const LValue &This,
10708 APValue &Result, EvalInfo &Info) {
10709 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10709, __extension__ __PRETTY_FUNCTION__))
;
10710 assert(E->isPRValue() && E->getType()->isArrayType() &&(static_cast <bool> (E->isPRValue() && E->
getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10711, __extension__ __PRETTY_FUNCTION__
))
10711 "not an array prvalue")(static_cast <bool> (E->isPRValue() && E->
getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10711, __extension__ __PRETTY_FUNCTION__
))
;
10712 return ArrayExprEvaluator(Info, This, Result).Visit(E);
10713}
10714
10715static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10716 APValue &Result, const InitListExpr *ILE,
10717 QualType AllocType) {
10718 assert(!ILE->isValueDependent())(static_cast <bool> (!ILE->isValueDependent()) ? void
(0) : __assert_fail ("!ILE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10718, __extension__ __PRETTY_FUNCTION__))
;
10719 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&(static_cast <bool> (ILE->isPRValue() && ILE
->getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10720, __extension__ __PRETTY_FUNCTION__
))
10720 "not an array prvalue")(static_cast <bool> (ILE->isPRValue() && ILE
->getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10720, __extension__ __PRETTY_FUNCTION__
))
;
10721 return ArrayExprEvaluator(Info, This, Result)
10722 .VisitInitListExpr(ILE, AllocType);
10723}
10724
10725static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10726 APValue &Result,
10727 const CXXConstructExpr *CCE,
10728 QualType AllocType) {
10729 assert(!CCE->isValueDependent())(static_cast <bool> (!CCE->isValueDependent()) ? void
(0) : __assert_fail ("!CCE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10729, __extension__ __PRETTY_FUNCTION__))
;
10730 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&(static_cast <bool> (CCE->isPRValue() && CCE
->getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10731, __extension__ __PRETTY_FUNCTION__
))
10731 "not an array prvalue")(static_cast <bool> (CCE->isPRValue() && CCE
->getType()->isArrayType() && "not an array prvalue"
) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\""
, "clang/lib/AST/ExprConstant.cpp", 10731, __extension__ __PRETTY_FUNCTION__
))
;
10732 return ArrayExprEvaluator(Info, This, Result)
10733 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10734}
10735
10736// Return true iff the given array filler may depend on the element index.
10737static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10738 // For now, just allow non-class value-initialization and initialization
10739 // lists comprised of them.
10740 if (isa<ImplicitValueInitExpr>(FillerExpr))
10741 return false;
10742 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10743 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10744 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10745 return true;
10746 }
10747
10748 if (ILE->hasArrayFiller() &&
10749 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10750 return true;
10751
10752 return false;
10753 }
10754 return true;
10755}
10756
10757bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10758 QualType AllocType) {
10759 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10760 AllocType.isNull() ? E->getType() : AllocType);
10761 if (!CAT)
10762 return Error(E);
10763
10764 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10765 // an appropriately-typed string literal enclosed in braces.
10766 if (E->isStringLiteralInit()) {
10767 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10768 // FIXME: Support ObjCEncodeExpr here once we support it in
10769 // ArrayExprEvaluator generally.
10770 if (!SL)
10771 return Error(E);
10772 return VisitStringLiteral(SL, AllocType);
10773 }
10774 // Any other transparent list init will need proper handling of the
10775 // AllocType; we can't just recurse to the inner initializer.
10776 assert(!E->isTransparent() &&(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?"
) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\""
, "clang/lib/AST/ExprConstant.cpp", 10777, __extension__ __PRETTY_FUNCTION__
))
10777 "transparent array list initialization is not string literal init?")(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?"
) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\""
, "clang/lib/AST/ExprConstant.cpp", 10777, __extension__ __PRETTY_FUNCTION__
))
;
10778
10779 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10780 AllocType);
10781}
10782
10783bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
10784 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
10785 QualType AllocType) {
10786 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10787 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
10788
10789 bool Success = true;
10790
10791 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts
() == 0) && "zero-initialized array shouldn't have any initialized elts"
) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "clang/lib/AST/ExprConstant.cpp", 10792, __extension__ __PRETTY_FUNCTION__
))
10792 "zero-initialized array shouldn't have any initialized elts")(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts
() == 0) && "zero-initialized array shouldn't have any initialized elts"
) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "clang/lib/AST/ExprConstant.cpp", 10792, __extension__ __PRETTY_FUNCTION__
))
;
10793 APValue Filler;
10794 if (Result.isArray() && Result.hasArrayFiller())
10795 Filler = Result.getArrayFiller();
10796
10797 unsigned NumEltsToInit = Args.size();
10798 unsigned NumElts = CAT->getSize().getZExtValue();
10799
10800 // If the initializer might depend on the array index, run it for each
10801 // array element.
10802 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
10803 NumEltsToInit = NumElts;
10804
10805 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: "
<< NumEltsToInit << ".\n"; } } while (false)
10806 << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: "
<< NumEltsToInit << ".\n"; } } while (false)
;
10807
10808 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10809
10810 // If the array was previously zero-initialized, preserve the
10811 // zero-initialized values.
10812 if (Filler.hasValue()) {
10813 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10814 Result.getArrayInitializedElt(I) = Filler;
10815 if (Result.hasArrayFiller())
10816 Result.getArrayFiller() = Filler;
10817 }
10818
10819 LValue Subobject = This;
10820 Subobject.addArray(Info, ExprToVisit, CAT);
10821 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10822 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
10823 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10824 Info, Subobject, Init) ||
10825 !HandleLValueArrayAdjustment(Info, Init, Subobject,
10826 CAT->getElementType(), 1)) {
10827 if (!Info.noteFailure())
10828 return false;
10829 Success = false;
10830 }
10831 }
10832
10833 if (!Result.hasArrayFiller())
10834 return Success;
10835
10836 // If we get here, we have a trivial filler, which we can just evaluate
10837 // once and splat over the rest of the array elements.
10838 assert(ArrayFiller && "no array filler for incomplete init list")(static_cast <bool> (ArrayFiller && "no array filler for incomplete init list"
) ? void (0) : __assert_fail ("ArrayFiller && \"no array filler for incomplete init list\""
, "clang/lib/AST/ExprConstant.cpp", 10838, __extension__ __PRETTY_FUNCTION__
))
;
10839 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10840 ArrayFiller) &&
10841 Success;
10842}
10843
10844bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10845 LValue CommonLV;
10846 if (E->getCommonExpr() &&
10847 !Evaluate(Info.CurrentCall->createTemporary(
10848 E->getCommonExpr(),
10849 getStorageType(Info.Ctx, E->getCommonExpr()),
10850 ScopeKind::FullExpression, CommonLV),
10851 Info, E->getCommonExpr()->getSourceExpr()))
10852 return false;
10853
10854 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10855
10856 uint64_t Elements = CAT->getSize().getZExtValue();
10857 Result = APValue(APValue::UninitArray(), Elements, Elements);
10858
10859 LValue Subobject = This;
10860 Subobject.addArray(Info, E, CAT);
10861
10862 bool Success = true;
10863 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10864 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10865 Info, Subobject, E->getSubExpr()) ||
10866 !HandleLValueArrayAdjustment(Info, E, Subobject,
10867 CAT->getElementType(), 1)) {
10868 if (!Info.noteFailure())
10869 return false;
10870 Success = false;
10871 }
10872 }
10873
10874 return Success;
10875}
10876
10877bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10878 return VisitCXXConstructExpr(E, This, &Result, E->getType());
10879}
10880
10881bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10882 const LValue &Subobject,
10883 APValue *Value,
10884 QualType Type) {
10885 bool HadZeroInit = Value->hasValue();
10886
10887 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10888 unsigned FinalSize = CAT->getSize().getZExtValue();
10889
10890 // Preserve the array filler if we had prior zero-initialization.
10891 APValue Filler =
10892 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10893 : APValue();
10894
10895 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10896 if (FinalSize == 0)
10897 return true;
10898
10899 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10900 Info, E->getExprLoc(), E->getConstructor(),
10901 E->requiresZeroInitialization());
10902 LValue ArrayElt = Subobject;
10903 ArrayElt.addArray(Info, E, CAT);
10904 // We do the whole initialization in two passes, first for just one element,
10905 // then for the whole array. It's possible we may find out we can't do const
10906 // init in the first pass, in which case we avoid allocating a potentially
10907 // large array. We don't do more passes because expanding array requires
10908 // copying the data, which is wasteful.
10909 for (const unsigned N : {1u, FinalSize}) {
10910 unsigned OldElts = Value->getArrayInitializedElts();
10911 if (OldElts == N)
10912 break;
10913
10914 // Expand the array to appropriate size.
10915 APValue NewValue(APValue::UninitArray(), N, FinalSize);
10916 for (unsigned I = 0; I < OldElts; ++I)
10917 NewValue.getArrayInitializedElt(I).swap(
10918 Value->getArrayInitializedElt(I));
10919 Value->swap(NewValue);
10920
10921 if (HadZeroInit)
10922 for (unsigned I = OldElts; I < N; ++I)
10923 Value->getArrayInitializedElt(I) = Filler;
10924
10925 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
10926 // If we have a trivial constructor, only evaluate it once and copy
10927 // the result into all the array elements.
10928 APValue &FirstResult = Value->getArrayInitializedElt(0);
10929 for (unsigned I = OldElts; I < FinalSize; ++I)
10930 Value->getArrayInitializedElt(I) = FirstResult;
10931 } else {
10932 for (unsigned I = OldElts; I < N; ++I) {
10933 if (!VisitCXXConstructExpr(E, ArrayElt,
10934 &Value->getArrayInitializedElt(I),
10935 CAT->getElementType()) ||
10936 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10937 CAT->getElementType(), 1))
10938 return false;
10939 // When checking for const initilization any diagnostic is considered
10940 // an error.
10941 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10942 !Info.keepEvaluatingAfterFailure())
10943 return false;
10944 }
10945 }
10946 }
10947
10948 return true;
10949 }
10950
10951 if (!Type->isRecordType())
10952 return Error(E);
10953
10954 return RecordExprEvaluator(Info, Subobject, *Value)
10955 .VisitCXXConstructExpr(E, Type);
10956}
10957
10958bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
10959 const CXXParenListInitExpr *E) {
10960 assert(dyn_cast<ConstantArrayType>(E->getType()) &&(static_cast <bool> (dyn_cast<ConstantArrayType>(
E->getType()) && "Expression result is not a constant array type"
) ? void (0) : __assert_fail ("dyn_cast<ConstantArrayType>(E->getType()) && \"Expression result is not a constant array type\""
, "clang/lib/AST/ExprConstant.cpp", 10961, __extension__ __PRETTY_FUNCTION__
))
10961 "Expression result is not a constant array type")(static_cast <bool> (dyn_cast<ConstantArrayType>(
E->getType()) && "Expression result is not a constant array type"
) ? void (0) : __assert_fail ("dyn_cast<ConstantArrayType>(E->getType()) && \"Expression result is not a constant array type\""
, "clang/lib/AST/ExprConstant.cpp", 10961, __extension__ __PRETTY_FUNCTION__
))
;
10962
10963 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
10964 E->getArrayFiller());
10965}
10966
10967//===----------------------------------------------------------------------===//
10968// Integer Evaluation
10969//
10970// As a GNU extension, we support casting pointers to sufficiently-wide integer
10971// types and back in constant folding. Integer values are thus represented
10972// either as an integer-valued APValue, or as an lvalue-valued APValue.
10973//===----------------------------------------------------------------------===//
10974
10975namespace {
10976class IntExprEvaluator
10977 : public ExprEvaluatorBase<IntExprEvaluator> {
10978 APValue &Result;
10979public:
10980 IntExprEvaluator(EvalInfo &info, APValue &result)
10981 : ExprEvaluatorBaseTy(info), Result(result) {}
10982
10983 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10984 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10985, __extension__ __PRETTY_FUNCTION__
))
10985 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10985, __extension__ __PRETTY_FUNCTION__
))
;
10986 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&(static_cast <bool> (SI.isSigned() == E->getType()->
isSignedIntegerOrEnumerationType() && "Invalid evaluation result."
) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10987, __extension__ __PRETTY_FUNCTION__
))
10987 "Invalid evaluation result.")(static_cast <bool> (SI.isSigned() == E->getType()->
isSignedIntegerOrEnumerationType() && "Invalid evaluation result."
) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10987, __extension__ __PRETTY_FUNCTION__
))
;
10988 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10989, __extension__ __PRETTY_FUNCTION__
))
10989 "Invalid evaluation result.")(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10989, __extension__ __PRETTY_FUNCTION__
))
;
10990 Result = APValue(SI);
10991 return true;
10992 }
10993 bool Success(const llvm::APSInt &SI, const Expr *E) {
10994 return Success(SI, E, Result);
10995 }
10996
10997 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10998 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10999, __extension__ __PRETTY_FUNCTION__
))
10999 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 10999, __extension__ __PRETTY_FUNCTION__
))
;
11000 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11001, __extension__ __PRETTY_FUNCTION__
))
11001 "Invalid evaluation result.")(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11001, __extension__ __PRETTY_FUNCTION__
))
;
11002 Result = APValue(APSInt(I));
11003 Result.getInt().setIsUnsigned(
11004 E->getType()->isUnsignedIntegerOrEnumerationType());
11005 return true;
11006 }
11007 bool Success(const llvm::APInt &I, const Expr *E) {
11008 return Success(I, E, Result);
11009 }
11010
11011 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11012 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11013, __extension__ __PRETTY_FUNCTION__
))
11013 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11013, __extension__ __PRETTY_FUNCTION__
))
;
11014 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11015 return true;
11016 }
11017 bool Success(uint64_t Value, const Expr *E) {
11018 return Success(Value, E, Result);
11019 }
11020
11021 bool Success(CharUnits Size, const Expr *E) {
11022 return Success(Size.getQuantity(), E);
11023 }
11024
11025 bool Success(const APValue &V, const Expr *E) {
11026 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11027 Result = V;
11028 return true;
11029 }
11030 return Success(V.getInt(), E);
11031 }
11032
11033 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11034
11035 //===--------------------------------------------------------------------===//
11036 // Visitor Methods
11037 //===--------------------------------------------------------------------===//
11038
11039 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11040 return Success(E->getValue(), E);
11041 }
11042 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11043 return Success(E->getValue(), E);
11044 }
11045
11046 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11047 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11048 if (CheckReferencedDecl(E, E->getDecl()))
11049 return true;
11050
11051 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11052 }
11053 bool VisitMemberExpr(const MemberExpr *E) {
11054 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11055 VisitIgnoredBaseExpression(E->getBase());
11056 return true;
11057 }
11058
11059 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11060 }
11061
11062 bool VisitCallExpr(const CallExpr *E);
11063 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11064 bool VisitBinaryOperator(const BinaryOperator *E);
11065 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11066 bool VisitUnaryOperator(const UnaryOperator *E);
11067
11068 bool VisitCastExpr(const CastExpr* E);
11069 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11070
11071 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11072 return Success(E->getValue(), E);
11073 }
11074
11075 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11076 return Success(E->getValue(), E);
11077 }
11078
11079 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11080 if (Info.ArrayInitIndex == uint64_t(-1)) {
11081 // We were asked to evaluate this subexpression independent of the
11082 // enclosing ArrayInitLoopExpr. We can't do that.
11083 Info.FFDiag(E);
11084 return false;
11085 }
11086 return Success(Info.ArrayInitIndex, E);
11087 }
11088
11089 // Note, GNU defines __null as an integer, not a pointer.
11090 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11091 return ZeroInitialization(E);
11092 }
11093
11094 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11095 return Success(E->getValue(), E);
11096 }
11097
11098 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11099 return Success(E->getValue(), E);
11100 }
11101
11102 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11103 return Success(E->getValue(), E);
11104 }
11105
11106 bool VisitUnaryReal(const UnaryOperator *E);
11107 bool VisitUnaryImag(const UnaryOperator *E);
11108
11109 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11110 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11111 bool VisitSourceLocExpr(const SourceLocExpr *E);
11112 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11113 bool VisitRequiresExpr(const RequiresExpr *E);
11114 // FIXME: Missing: array subscript of vector, member of vector
11115};
11116
11117class FixedPointExprEvaluator
11118 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11119 APValue &Result;
11120
11121 public:
11122 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11123 : ExprEvaluatorBaseTy(info), Result(result) {}
11124
11125 bool Success(const llvm::APInt &I, const Expr *E) {
11126 return Success(
11127 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11128 }
11129
11130 bool Success(uint64_t Value, const Expr *E) {
11131 return Success(
11132 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11133 }
11134
11135 bool Success(const APValue &V, const Expr *E) {
11136 return Success(V.getFixedPoint(), E);
11137 }
11138
11139 bool Success(const APFixedPoint &V, const Expr *E) {
11140 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")(static_cast <bool> (E->getType()->isFixedPointType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isFixedPointType() && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11140, __extension__ __PRETTY_FUNCTION__
))
;
11141 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11142, __extension__ __PRETTY_FUNCTION__
))
11142 "Invalid evaluation result.")(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "clang/lib/AST/ExprConstant.cpp", 11142, __extension__ __PRETTY_FUNCTION__
))
;
11143 Result = APValue(V);
11144 return true;
11145 }
11146
11147 //===--------------------------------------------------------------------===//
11148 // Visitor Methods
11149 //===--------------------------------------------------------------------===//
11150
11151 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11152 return Success(E->getValue(), E);
11153 }
11154
11155 bool VisitCastExpr(const CastExpr *E);
11156 bool VisitUnaryOperator(const UnaryOperator *E);
11157 bool VisitBinaryOperator(const BinaryOperator *E);
11158};
11159} // end anonymous namespace
11160
11161/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11162/// produce either the integer value or a pointer.
11163///
11164/// GCC has a heinous extension which folds casts between pointer types and
11165/// pointer-sized integral types. We support this by allowing the evaluation of
11166/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11167/// Some simple arithmetic on such values is supported (they are treated much
11168/// like char*).
11169static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11170 EvalInfo &Info) {
11171 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11171, __extension__ __PRETTY_FUNCTION__))
;
11172 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->isPRValue() && E->
getType()->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("E->isPRValue() && E->getType()->isIntegralOrEnumerationType()"
, "clang/lib/AST/ExprConstant.cpp", 11172, __extension__ __PRETTY_FUNCTION__
))
;
11173 return IntExprEvaluator(Info, Result).Visit(E);
11174}
11175
11176static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11177 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11177, __extension__ __PRETTY_FUNCTION__))
;
11178 APValue Val;
11179 if (!EvaluateIntegerOrLValue(E, Val, Info))
11180 return false;
11181 if (!Val.isInt()) {
11182 // FIXME: It would be better to produce the diagnostic for casting
11183 // a pointer to an integer.
11184 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11185 return false;
11186 }
11187 Result = Val.getInt();
11188 return true;
11189}
11190
11191bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11192 APValue Evaluated = E->EvaluateInContext(
11193 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11194 return Success(Evaluated, E);
11195}
11196
11197static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11198 EvalInfo &Info) {
11199 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11199, __extension__ __PRETTY_FUNCTION__))
;
11200 if (E->getType()->isFixedPointType()) {
11201 APValue Val;
11202 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11203 return false;
11204 if (!Val.isFixedPoint())
11205 return false;
11206
11207 Result = Val.getFixedPoint();
11208 return true;
11209 }
11210 return false;
11211}
11212
11213static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11214 EvalInfo &Info) {
11215 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11215, __extension__ __PRETTY_FUNCTION__))
;
11216 if (E->getType()->isIntegerType()) {
11217 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11218 APSInt Val;
11219 if (!EvaluateInteger(E, Val, Info))
11220 return false;
11221 Result = APFixedPoint(Val, FXSema);
11222 return true;
11223 } else if (E->getType()->isFixedPointType()) {
11224 return EvaluateFixedPoint(E, Result, Info);
11225 }
11226 return false;
11227}
11228
11229/// Check whether the given declaration can be directly converted to an integral
11230/// rvalue. If not, no diagnostic is produced; there are other things we can
11231/// try.
11232bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11233 // Enums are integer constant exprs.
11234 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11235 // Check for signedness/width mismatches between E type and ECD value.
11236 bool SameSign = (ECD->getInitVal().isSigned()
11237 == E->getType()->isSignedIntegerOrEnumerationType());
11238 bool SameWidth = (ECD->getInitVal().getBitWidth()
11239 == Info.Ctx.getIntWidth(E->getType()));
11240 if (SameSign && SameWidth)
11241 return Success(ECD->getInitVal(), E);
11242 else {
11243 // Get rid of mismatch (otherwise Success assertions will fail)
11244 // by computing a new value matching the type of E.
11245 llvm::APSInt Val = ECD->getInitVal();
11246 if (!SameSign)
11247 Val.setIsSigned(!ECD->getInitVal().isSigned());
11248 if (!SameWidth)
11249 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11250 return Success(Val, E);
11251 }
11252 }
11253 return false;
11254}
11255
11256/// Values returned by __builtin_classify_type, chosen to match the values
11257/// produced by GCC's builtin.
11258enum class GCCTypeClass {
11259 None = -1,
11260 Void = 0,
11261 Integer = 1,
11262 // GCC reserves 2 for character types, but instead classifies them as
11263 // integers.
11264 Enum = 3,
11265 Bool = 4,
11266 Pointer = 5,
11267 // GCC reserves 6 for references, but appears to never use it (because
11268 // expressions never have reference type, presumably).
11269 PointerToDataMember = 7,
11270 RealFloat = 8,
11271 Complex = 9,
11272 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11273 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11274 // GCC claims to reserve 11 for pointers to member functions, but *actually*
11275 // uses 12 for that purpose, same as for a class or struct. Maybe it
11276 // internally implements a pointer to member as a struct? Who knows.
11277 PointerToMemberFunction = 12, // Not a bug, see above.
11278 ClassOrStruct = 12,
11279 Union = 13,
11280 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11281 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11282 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11283 // literals.
11284};
11285
11286/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11287/// as GCC.
11288static GCCTypeClass
11289EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11290 assert(!T->isDependentType() && "unexpected dependent type")(static_cast <bool> (!T->isDependentType() &&
"unexpected dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\""
, "clang/lib/AST/ExprConstant.cpp", 11290, __extension__ __PRETTY_FUNCTION__
))
;
11291
11292 QualType CanTy = T.getCanonicalType();
11293 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11294
11295 switch (CanTy->getTypeClass()) {
11296#define TYPE(ID, BASE)
11297#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11298#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11299#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11300#include "clang/AST/TypeNodes.inc"
11301 case Type::Auto:
11302 case Type::DeducedTemplateSpecialization:
11303 llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type"
, "clang/lib/AST/ExprConstant.cpp", 11303)
;
11304
11305 case Type::Builtin:
11306 switch (BT->getKind()) {
11307#define BUILTIN_TYPE(ID, SINGLETON_ID)
11308#define SIGNED_TYPE(ID, SINGLETON_ID) \
11309 case BuiltinType::ID: return GCCTypeClass::Integer;
11310#define FLOATING_TYPE(ID, SINGLETON_ID) \
11311 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11312#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11313 case BuiltinType::ID: break;
11314#include "clang/AST/BuiltinTypes.def"
11315 case BuiltinType::Void:
11316 return GCCTypeClass::Void;
11317
11318 case BuiltinType::Bool:
11319 return GCCTypeClass::Bool;
11320
11321 case BuiltinType::Char_U:
11322 case BuiltinType::UChar:
11323 case BuiltinType::WChar_U:
11324 case BuiltinType::Char8:
11325 case BuiltinType::Char16:
11326 case BuiltinType::Char32:
11327 case BuiltinType::UShort:
11328 case BuiltinType::UInt:
11329 case BuiltinType::ULong:
11330 case BuiltinType::ULongLong:
11331 case BuiltinType::UInt128:
11332 return GCCTypeClass::Integer;
11333
11334 case BuiltinType::UShortAccum:
11335 case BuiltinType::UAccum:
11336 case BuiltinType::ULongAccum:
11337 case BuiltinType::UShortFract:
11338 case BuiltinType::UFract:
11339 case BuiltinType::ULongFract:
11340 case BuiltinType::SatUShortAccum:
11341 case BuiltinType::SatUAccum:
11342 case BuiltinType::SatULongAccum:
11343 case BuiltinType::SatUShortFract:
11344 case BuiltinType::SatUFract:
11345 case BuiltinType::SatULongFract:
11346 return GCCTypeClass::None;
11347
11348 case BuiltinType::NullPtr:
11349
11350 case BuiltinType::ObjCId:
11351 case BuiltinType::ObjCClass:
11352 case BuiltinType::ObjCSel:
11353#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11354 case BuiltinType::Id:
11355#include "clang/Basic/OpenCLImageTypes.def"
11356#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11357 case BuiltinType::Id:
11358#include "clang/Basic/OpenCLExtensionTypes.def"
11359 case BuiltinType::OCLSampler:
11360 case BuiltinType::OCLEvent:
11361 case BuiltinType::OCLClkEvent:
11362 case BuiltinType::OCLQueue:
11363 case BuiltinType::OCLReserveID:
11364#define SVE_TYPE(Name, Id, SingletonId) \
11365 case BuiltinType::Id:
11366#include "clang/Basic/AArch64SVEACLETypes.def"
11367#define PPC_VECTOR_TYPE(Name, Id, Size) \
11368 case BuiltinType::Id:
11369#include "clang/Basic/PPCTypes.def"
11370#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11371#include "clang/Basic/RISCVVTypes.def"
11372#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11373#include "clang/Basic/WebAssemblyReferenceTypes.def"
11374 return GCCTypeClass::None;
11375
11376 case BuiltinType::Dependent:
11377 llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type"
, "clang/lib/AST/ExprConstant.cpp", 11377)
;
11378 };
11379 llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type"
, "clang/lib/AST/ExprConstant.cpp", 11379)
;
11380
11381 case Type::Enum:
11382 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11383
11384 case Type::Pointer:
11385 case Type::ConstantArray:
11386 case Type::VariableArray:
11387 case Type::IncompleteArray:
11388 case Type::FunctionNoProto:
11389 case Type::FunctionProto:
11390 return GCCTypeClass::Pointer;
11391
11392 case Type::MemberPointer:
11393 return CanTy->isMemberDataPointerType()
11394 ? GCCTypeClass::PointerToDataMember
11395 : GCCTypeClass::PointerToMemberFunction;
11396
11397 case Type::Complex:
11398 return GCCTypeClass::Complex;
11399
11400 case Type::Record:
11401 return CanTy->isUnionType() ? GCCTypeClass::Union
11402 : GCCTypeClass::ClassOrStruct;
11403
11404 case Type::Atomic:
11405 // GCC classifies _Atomic T the same as T.
11406 return EvaluateBuiltinClassifyType(
11407 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11408
11409 case Type::BlockPointer:
11410 case Type::Vector:
11411 case Type::ExtVector:
11412 case Type::ConstantMatrix:
11413 case Type::ObjCObject:
11414 case Type::ObjCInterface:
11415 case Type::ObjCObjectPointer:
11416 case Type::Pipe:
11417 case Type::BitInt:
11418 // GCC classifies vectors as None. We follow its lead and classify all
11419 // other types that don't fit into the regular classification the same way.
11420 return GCCTypeClass::None;
11421
11422 case Type::LValueReference:
11423 case Type::RValueReference:
11424 llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression"
, "clang/lib/AST/ExprConstant.cpp", 11424)
;
11425 }
11426
11427 llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "clang/lib/AST/ExprConstant.cpp"
, 11427)
;
11428}
11429
11430/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11431/// as GCC.
11432static GCCTypeClass
11433EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11434 // If no argument was supplied, default to None. This isn't
11435 // ideal, however it is what gcc does.
11436 if (E->getNumArgs() == 0)
11437 return GCCTypeClass::None;
11438
11439 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11440 // being an ICE, but still folds it to a constant using the type of the first
11441 // argument.
11442 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11443}
11444
11445/// EvaluateBuiltinConstantPForLValue - Determine the result of
11446/// __builtin_constant_p when applied to the given pointer.
11447///
11448/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11449/// or it points to the first character of a string literal.
11450static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11451 APValue::LValueBase Base = LV.getLValueBase();
11452 if (Base.isNull()) {
11453 // A null base is acceptable.
11454 return true;
11455 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11456 if (!isa<StringLiteral>(E))
11457 return false;
11458 return LV.getLValueOffset().isZero();
11459 } else if (Base.is<TypeInfoLValue>()) {
11460 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11461 // evaluate to true.
11462 return true;
11463 } else {
11464 // Any other base is not constant enough for GCC.
11465 return false;
11466 }
11467}
11468
11469/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11470/// GCC as we can manage.
11471static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11472 // This evaluation is not permitted to have side-effects, so evaluate it in
11473 // a speculative evaluation context.
11474 SpeculativeEvaluationRAII SpeculativeEval(Info);
11475
11476 // Constant-folding is always enabled for the operand of __builtin_constant_p
11477 // (even when the enclosing evaluation context otherwise requires a strict
11478 // language-specific constant expression).
11479 FoldConstant Fold(Info, true);
11480
11481 QualType ArgType = Arg->getType();
11482
11483 // __builtin_constant_p always has one operand. The rules which gcc follows
11484 // are not precisely documented, but are as follows:
11485 //
11486 // - If the operand is of integral, floating, complex or enumeration type,
11487 // and can be folded to a known value of that type, it returns 1.
11488 // - If the operand can be folded to a pointer to the first character
11489 // of a string literal (or such a pointer cast to an integral type)
11490 // or to a null pointer or an integer cast to a pointer, it returns 1.
11491 //
11492 // Otherwise, it returns 0.
11493 //
11494 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11495 // its support for this did not work prior to GCC 9 and is not yet well
11496 // understood.
11497 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11498 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11499 ArgType->isNullPtrType()) {
11500 APValue V;
11501 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11502 Fold.keepDiagnostics();
11503 return false;
11504 }
11505
11506 // For a pointer (possibly cast to integer), there are special rules.
11507 if (V.getKind() == APValue::LValue)
11508 return EvaluateBuiltinConstantPForLValue(V);
11509
11510 // Otherwise, any constant value is good enough.
11511 return V.hasValue();
11512 }
11513
11514 // Anything else isn't considered to be sufficiently constant.
11515 return false;
11516}
11517
11518/// Retrieves the "underlying object type" of the given expression,
11519/// as used by __builtin_object_size.
11520static QualType getObjectType(APValue::LValueBase B) {
11521 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11522 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11523 return VD->getType();
11524 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11525 if (isa<CompoundLiteralExpr>(E))
11526 return E->getType();
11527 } else if (B.is<TypeInfoLValue>()) {
11528 return B.getTypeInfoType();
11529 } else if (B.is<DynamicAllocLValue>()) {
11530 return B.getDynamicAllocType();
11531 }
11532
11533 return QualType();
11534}
11535
11536/// A more selective version of E->IgnoreParenCasts for
11537/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11538/// to change the type of E.
11539/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11540///
11541/// Always returns an RValue with a pointer representation.
11542static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11543 assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E->
getType()->hasPointerRepresentation()) ? void (0) : __assert_fail
("E->isPRValue() && E->getType()->hasPointerRepresentation()"
, "clang/lib/AST/ExprConstant.cpp", 11543, __extension__ __PRETTY_FUNCTION__
))
;
11544
11545 auto *NoParens = E->IgnoreParens();
11546 auto *Cast = dyn_cast<CastExpr>(NoParens);
11547 if (Cast == nullptr)
11548 return NoParens;
11549
11550 // We only conservatively allow a few kinds of casts, because this code is
11551 // inherently a simple solution that seeks to support the common case.
11552 auto CastKind = Cast->getCastKind();
11553 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11554 CastKind != CK_AddressSpaceConversion)
11555 return NoParens;
11556
11557 auto *SubExpr = Cast->getSubExpr();
11558 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11559 return NoParens;
11560 return ignorePointerCastsAndParens(SubExpr);
11561}
11562
11563/// Checks to see if the given LValue's Designator is at the end of the LValue's
11564/// record layout. e.g.
11565/// struct { struct { int a, b; } fst, snd; } obj;
11566/// obj.fst // no
11567/// obj.snd // yes
11568/// obj.fst.a // no
11569/// obj.fst.b // no
11570/// obj.snd.a // no
11571/// obj.snd.b // yes
11572///
11573/// Please note: this function is specialized for how __builtin_object_size
11574/// views "objects".
11575///
11576/// If this encounters an invalid RecordDecl or otherwise cannot determine the
11577/// correct result, it will always return true.
11578static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11579 assert(!LVal.Designator.Invalid)(static_cast <bool> (!LVal.Designator.Invalid) ? void (
0) : __assert_fail ("!LVal.Designator.Invalid", "clang/lib/AST/ExprConstant.cpp"
, 11579, __extension__ __PRETTY_FUNCTION__))
;
11580
11581 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11582 const RecordDecl *Parent = FD->getParent();
11583 Invalid = Parent->isInvalidDecl();
11584 if (Invalid || Parent->isUnion())
11585 return true;
11586 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11587 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11588 };
11589
11590 auto &Base = LVal.getLValueBase();
11591 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11592 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11593 bool Invalid;
11594 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11595 return Invalid;
11596 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11597 for (auto *FD : IFD->chain()) {
11598 bool Invalid;
11599 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11600 return Invalid;
11601 }
11602 }
11603 }
11604
11605 unsigned I = 0;
11606 QualType BaseType = getType(Base);
11607 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11608 // If we don't know the array bound, conservatively assume we're looking at
11609 // the final array element.
11610 ++I;
11611 if (BaseType->isIncompleteArrayType())
11612 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11613 else
11614 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11615 }
11616
11617 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11618 const auto &Entry = LVal.Designator.Entries[I];
11619 if (BaseType->isArrayType()) {
11620 // Because __builtin_object_size treats arrays as objects, we can ignore
11621 // the index iff this is the last array in the Designator.
11622 if (I + 1 == E)
11623 return true;
11624 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11625 uint64_t Index = Entry.getAsArrayIndex();
11626 if (Index + 1 != CAT->getSize())
11627 return false;
11628 BaseType = CAT->getElementType();
11629 } else if (BaseType->isAnyComplexType()) {
11630 const auto *CT = BaseType->castAs<ComplexType>();
11631 uint64_t Index = Entry.getAsArrayIndex();
11632 if (Index != 1)
11633 return false;
11634 BaseType = CT->getElementType();
11635 } else if (auto *FD = getAsField(Entry)) {
11636 bool Invalid;
11637 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11638 return Invalid;
11639 BaseType = FD->getType();
11640 } else {
11641 assert(getAsBaseClass(Entry) && "Expecting cast to a base class")(static_cast <bool> (getAsBaseClass(Entry) && "Expecting cast to a base class"
) ? void (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\""
, "clang/lib/AST/ExprConstant.cpp", 11641, __extension__ __PRETTY_FUNCTION__
))
;
11642 return false;
11643 }
11644 }
11645 return true;
11646}
11647
11648/// Tests to see if the LValue has a user-specified designator (that isn't
11649/// necessarily valid). Note that this always returns 'true' if the LValue has
11650/// an unsized array as its first designator entry, because there's currently no
11651/// way to tell if the user typed *foo or foo[0].
11652static bool refersToCompleteObject(const LValue &LVal) {
11653 if (LVal.Designator.Invalid)
11654 return false;
11655
11656 if (!LVal.Designator.Entries.empty())
11657 return LVal.Designator.isMostDerivedAnUnsizedArray();
11658
11659 if (!LVal.InvalidBase)
11660 return true;
11661
11662 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11663 // the LValueBase.
11664 const auto *E = LVal.Base.dyn_cast<const Expr *>();
11665 return !E || !isa<MemberExpr>(E);
11666}
11667
11668/// Attempts to detect a user writing into a piece of memory that's impossible
11669/// to figure out the size of by just using types.
11670static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11671 const SubobjectDesignator &Designator = LVal.Designator;
11672 // Notes:
11673 // - Users can only write off of the end when we have an invalid base. Invalid
11674 // bases imply we don't know where the memory came from.
11675 // - We used to be a bit more aggressive here; we'd only be conservative if
11676 // the array at the end was flexible, or if it had 0 or 1 elements. This
11677 // broke some common standard library extensions (PR30346), but was
11678 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11679 // with some sort of list. OTOH, it seems that GCC is always
11680 // conservative with the last element in structs (if it's an array), so our
11681 // current behavior is more compatible than an explicit list approach would
11682 // be.
11683 auto isFlexibleArrayMember = [&] {
11684 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11685 FAMKind StrictFlexArraysLevel =
11686 Ctx.getLangOpts().getStrictFlexArraysLevel();
11687
11688 if (Designator.isMostDerivedAnUnsizedArray())
11689 return true;
11690
11691 if (StrictFlexArraysLevel == FAMKind::Default)
11692 return true;
11693
11694 if (Designator.getMostDerivedArraySize() == 0 &&
11695 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11696 return true;
11697
11698 if (Designator.getMostDerivedArraySize() == 1 &&
11699 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11700 return true;
11701
11702 return false;
11703 };
11704
11705 return LVal.InvalidBase &&
11706 Designator.Entries.size() == Designator.MostDerivedPathLength &&
11707 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11708 isDesignatorAtObjectEnd(Ctx, LVal);
11709}
11710
11711/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11712/// Fails if the conversion would cause loss of precision.
11713static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11714 CharUnits &Result) {
11715 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11716 if (Int.ugt(CharUnitsMax))
11717 return false;
11718 Result = CharUnits::fromQuantity(Int.getZExtValue());
11719 return true;
11720}
11721
11722/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11723/// determine how many bytes exist from the beginning of the object to either
11724/// the end of the current subobject, or the end of the object itself, depending
11725/// on what the LValue looks like + the value of Type.
11726///
11727/// If this returns false, the value of Result is undefined.
11728static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11729 unsigned Type, const LValue &LVal,
11730 CharUnits &EndOffset) {
11731 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11732
11733 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11734 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11735 return false;
11736 return HandleSizeof(Info, ExprLoc, Ty, Result);
11737 };
11738
11739 // We want to evaluate the size of the entire object. This is a valid fallback
11740 // for when Type=1 and the designator is invalid, because we're asked for an
11741 // upper-bound.
11742 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11743 // Type=3 wants a lower bound, so we can't fall back to this.
11744 if (Type == 3 && !DetermineForCompleteObject)
11745 return false;
11746
11747 llvm::APInt APEndOffset;
11748 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11749 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11750 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11751
11752 if (LVal.InvalidBase)
11753 return false;
11754
11755 QualType BaseTy = getObjectType(LVal.getLValueBase());
11756 return CheckedHandleSizeof(BaseTy, EndOffset);
11757 }
11758
11759 // We want to evaluate the size of a subobject.
11760 const SubobjectDesignator &Designator = LVal.Designator;
11761
11762 // The following is a moderately common idiom in C:
11763 //
11764 // struct Foo { int a; char c[1]; };
11765 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11766 // strcpy(&F->c[0], Bar);
11767 //
11768 // In order to not break too much legacy code, we need to support it.
11769 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11770 // If we can resolve this to an alloc_size call, we can hand that back,
11771 // because we know for certain how many bytes there are to write to.
11772 llvm::APInt APEndOffset;
11773 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11774 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11775 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11776
11777 // If we cannot determine the size of the initial allocation, then we can't
11778 // given an accurate upper-bound. However, we are still able to give
11779 // conservative lower-bounds for Type=3.
11780 if (Type == 1)
11781 return false;
11782 }
11783
11784 CharUnits BytesPerElem;
11785 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11786 return false;
11787
11788 // According to the GCC documentation, we want the size of the subobject
11789 // denoted by the pointer. But that's not quite right -- what we actually
11790 // want is the size of the immediately-enclosing array, if there is one.
11791 int64_t ElemsRemaining;
11792 if (Designator.MostDerivedIsArrayElement &&
11793 Designator.Entries.size() == Designator.MostDerivedPathLength) {
11794 uint64_t ArraySize = Designator.getMostDerivedArraySize();
11795 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11796 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11797 } else {
11798 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11799 }
11800
11801 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11802 return true;
11803}
11804
11805/// Tries to evaluate the __builtin_object_size for @p E. If successful,
11806/// returns true and stores the result in @p Size.
11807///
11808/// If @p WasError is non-null, this will report whether the failure to evaluate
11809/// is to be treated as an Error in IntExprEvaluator.
11810static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11811 EvalInfo &Info, uint64_t &Size) {
11812 // Determine the denoted object.
11813 LValue LVal;
11814 {
11815 // The operand of __builtin_object_size is never evaluated for side-effects.
11816 // If there are any, but we can determine the pointed-to object anyway, then
11817 // ignore the side-effects.
11818 SpeculativeEvaluationRAII SpeculativeEval(Info);
11819 IgnoreSideEffectsRAII Fold(Info);
11820
11821 if (E->isGLValue()) {
11822 // It's possible for us to be given GLValues if we're called via
11823 // Expr::tryEvaluateObjectSize.
11824 APValue RVal;
11825 if (!EvaluateAsRValue(Info, E, RVal))
11826 return false;
11827 LVal.setFrom(Info.Ctx, RVal);
11828 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11829 /*InvalidBaseOK=*/true))
11830 return false;
11831 }
11832
11833 // If we point to before the start of the object, there are no accessible
11834 // bytes.
11835 if (LVal.getLValueOffset().isNegative()) {
11836 Size = 0;
11837 return true;
11838 }
11839
11840 CharUnits EndOffset;
11841 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11842 return false;
11843
11844 // If we've fallen outside of the end offset, just pretend there's nothing to
11845 // write to/read from.
11846 if (EndOffset <= LVal.getLValueOffset())
11847 Size = 0;
11848 else
11849 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11850 return true;
11851}
11852
11853bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11854 if (!IsConstantEvaluatedBuiltinCall(E))
11855 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11856 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11857}
11858
11859static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11860 APValue &Val, APSInt &Alignment) {
11861 QualType SrcTy = E->getArg(0)->getType();
11862 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11863 return false;
11864 // Even though we are evaluating integer expressions we could get a pointer
11865 // argument for the __builtin_is_aligned() case.
11866 if (SrcTy->isPointerType()) {
11867 LValue Ptr;
11868 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11869 return false;
11870 Ptr.moveInto(Val);
11871 } else if (!SrcTy->isIntegralOrEnumerationType()) {
11872 Info.FFDiag(E->getArg(0));
11873 return false;
11874 } else {
11875 APSInt SrcInt;
11876 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11877 return false;
11878 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&(static_cast <bool> (SrcInt.getBitWidth() >= Alignment
.getBitWidth() && "Bit widths must be the same") ? void
(0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\""
, "clang/lib/AST/ExprConstant.cpp", 11879, __extension__ __PRETTY_FUNCTION__
))
11879 "Bit widths must be the same")(static_cast <bool> (SrcInt.getBitWidth() >= Alignment
.getBitWidth() && "Bit widths must be the same") ? void
(0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\""
, "clang/lib/AST/ExprConstant.cpp", 11879, __extension__ __PRETTY_FUNCTION__
))
;
11880 Val = APValue(SrcInt);
11881 }
11882 assert(Val.hasValue())(static_cast <bool> (Val.hasValue()) ? void (0) : __assert_fail
("Val.hasValue()", "clang/lib/AST/ExprConstant.cpp", 11882, __extension__
__PRETTY_FUNCTION__))
;
11883 return true;
11884}
11885
11886bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11887 unsigned BuiltinOp) {
11888 switch (BuiltinOp) {
11889 default:
11890 return false;
11891
11892 case Builtin::BI__builtin_dynamic_object_size:
11893 case Builtin::BI__builtin_object_size: {
11894 // The type was checked when we built the expression.
11895 unsigned Type =
11896 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11897 assert(Type <= 3 && "unexpected type")(static_cast <bool> (Type <= 3 && "unexpected type"
) ? void (0) : __assert_fail ("Type <= 3 && \"unexpected type\""
, "clang/lib/AST/ExprConstant.cpp", 11897, __extension__ __PRETTY_FUNCTION__
))
;
11898
11899 uint64_t Size;
11900 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11901 return Success(Size, E);
11902
11903 if (E->getArg(0)->HasSideEffects(Info.Ctx))
11904 return Success((Type & 2) ? 0 : -1, E);
11905
11906 // Expression had no side effects, but we couldn't statically determine the
11907 // size of the referenced object.
11908 switch (Info.EvalMode) {
11909 case EvalInfo::EM_ConstantExpression:
11910 case EvalInfo::EM_ConstantFold:
11911 case EvalInfo::EM_IgnoreSideEffects:
11912 // Leave it to IR generation.
11913 return Error(E);
11914 case EvalInfo::EM_ConstantExpressionUnevaluated:
11915 // Reduce it to a constant now.
11916 return Success((Type & 2) ? 0 : -1, E);
11917 }
11918
11919 llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "clang/lib/AST/ExprConstant.cpp"
, 11919)
;
11920 }
11921
11922 case Builtin::BI__builtin_os_log_format_buffer_size: {
11923 analyze_os_log::OSLogBufferLayout Layout;
11924 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11925 return Success(Layout.size().getQuantity(), E);
11926 }
11927
11928 case Builtin::BI__builtin_is_aligned: {
11929 APValue Src;
11930 APSInt Alignment;
11931 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11932 return false;
11933 if (Src.isLValue()) {
11934 // If we evaluated a pointer, check the minimum known alignment.
11935 LValue Ptr;
11936 Ptr.setFrom(Info.Ctx, Src);
11937 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11938 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11939 // We can return true if the known alignment at the computed offset is
11940 // greater than the requested alignment.
11941 assert(PtrAlign.isPowerOfTwo())(static_cast <bool> (PtrAlign.isPowerOfTwo()) ? void (0
) : __assert_fail ("PtrAlign.isPowerOfTwo()", "clang/lib/AST/ExprConstant.cpp"
, 11941, __extension__ __PRETTY_FUNCTION__))
;
11942 assert(Alignment.isPowerOf2())(static_cast <bool> (Alignment.isPowerOf2()) ? void (0)
: __assert_fail ("Alignment.isPowerOf2()", "clang/lib/AST/ExprConstant.cpp"
, 11942, __extension__ __PRETTY_FUNCTION__))
;
11943 if (PtrAlign.getQuantity() >= Alignment)
11944 return Success(1, E);
11945 // If the alignment is not known to be sufficient, some cases could still
11946 // be aligned at run time. However, if the requested alignment is less or
11947 // equal to the base alignment and the offset is not aligned, we know that
11948 // the run-time value can never be aligned.
11949 if (BaseAlignment.getQuantity() >= Alignment &&
11950 PtrAlign.getQuantity() < Alignment)
11951 return Success(0, E);
11952 // Otherwise we can't infer whether the value is sufficiently aligned.
11953 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11954 // in cases where we can't fully evaluate the pointer.
11955 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11956 << Alignment;
11957 return false;
11958 }
11959 assert(Src.isInt())(static_cast <bool> (Src.isInt()) ? void (0) : __assert_fail
("Src.isInt()", "clang/lib/AST/ExprConstant.cpp", 11959, __extension__
__PRETTY_FUNCTION__))
;
11960 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11961 }
11962 case Builtin::BI__builtin_align_up: {
11963 APValue Src;
11964 APSInt Alignment;
11965 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11966 return false;
11967 if (!Src.isInt())
11968 return Error(E);
11969 APSInt AlignedVal =
11970 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11971 Src.getInt().isUnsigned());
11972 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt
().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()"
, "clang/lib/AST/ExprConstant.cpp", 11972, __extension__ __PRETTY_FUNCTION__
))
;
11973 return Success(AlignedVal, E);
11974 }
11975 case Builtin::BI__builtin_align_down: {
11976 APValue Src;
11977 APSInt Alignment;
11978 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11979 return false;
11980 if (!Src.isInt())
11981 return Error(E);
11982 APSInt AlignedVal =
11983 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11984 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt
().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()"
, "clang/lib/AST/ExprConstant.cpp", 11984, __extension__ __PRETTY_FUNCTION__
))
;
11985 return Success(AlignedVal, E);
11986 }
11987
11988 case Builtin::BI__builtin_bitreverse8:
11989 case Builtin::BI__builtin_bitreverse16:
11990 case Builtin::BI__builtin_bitreverse32:
11991 case Builtin::BI__builtin_bitreverse64: {
11992 APSInt Val;
11993 if (!EvaluateInteger(E->getArg(0), Val, Info))
11994 return false;
11995
11996 return Success(Val.reverseBits(), E);
11997 }
11998
11999 case Builtin::BI__builtin_bswap16:
12000 case Builtin::BI__builtin_bswap32:
12001 case Builtin::BI__builtin_bswap64: {
12002 APSInt Val;
12003 if (!EvaluateInteger(E->getArg(0), Val, Info))
12004 return false;
12005
12006 return Success(Val.byteSwap(), E);
12007 }
12008
12009 case Builtin::BI__builtin_classify_type:
12010 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12011
12012 case Builtin::BI__builtin_clrsb:
12013 case Builtin::BI__builtin_clrsbl:
12014 case Builtin::BI__builtin_clrsbll: {
12015 APSInt Val;
12016 if (!EvaluateInteger(E->getArg(0), Val, Info))
12017 return false;
12018
12019 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12020 }
12021
12022 case Builtin::BI__builtin_clz:
12023 case Builtin::BI__builtin_clzl:
12024 case Builtin::BI__builtin_clzll:
12025 case Builtin::BI__builtin_clzs: {
12026 APSInt Val;
12027 if (!EvaluateInteger(E->getArg(0), Val, Info))
12028 return false;
12029 if (!Val)
12030 return Error(E);
12031
12032 return Success(Val.countl_zero(), E);
12033 }
12034
12035 case Builtin::BI__builtin_constant_p: {
12036 const Expr *Arg = E->getArg(0);
12037 if (EvaluateBuiltinConstantP(Info, Arg))
12038 return Success(true, E);
12039 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12040 // Outside a constant context, eagerly evaluate to false in the presence
12041 // of side-effects in order to avoid -Wunsequenced false-positives in
12042 // a branch on __builtin_constant_p(expr).
12043 return Success(false, E);
12044 }
12045 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12046 return false;
12047 }
12048
12049 case Builtin::BI__builtin_is_constant_evaluated: {
12050 const auto *Callee = Info.CurrentCall->getCallee();
12051 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12052 (Info.CallStackDepth == 1 ||
12053 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12054 Callee->getIdentifier() &&
12055 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12056 // FIXME: Find a better way to avoid duplicated diagnostics.
12057 if (Info.EvalStatus.Diag)
12058 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12059 : Info.CurrentCall->CallLoc,
12060 diag::warn_is_constant_evaluated_always_true_constexpr)
12061 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12062 : "std::is_constant_evaluated");
12063 }
12064
12065 return Success(Info.InConstantContext, E);
12066 }
12067
12068 case Builtin::BI__builtin_ctz:
12069 case Builtin::BI__builtin_ctzl:
12070 case Builtin::BI__builtin_ctzll:
12071 case Builtin::BI__builtin_ctzs: {
12072 APSInt Val;
12073 if (!EvaluateInteger(E->getArg(0), Val, Info))
12074 return false;
12075 if (!Val)
12076 return Error(E);
12077
12078 return Success(Val.countr_zero(), E);
12079 }
12080
12081 case Builtin::BI__builtin_eh_return_data_regno: {
12082 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12083 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12084 return Success(Operand, E);
12085 }
12086
12087 case Builtin::BI__builtin_expect:
12088 case Builtin::BI__builtin_expect_with_probability:
12089 return Visit(E->getArg(0));
12090
12091 case Builtin::BI__builtin_ffs:
12092 case Builtin::BI__builtin_ffsl:
12093 case Builtin::BI__builtin_ffsll: {
12094 APSInt Val;
12095 if (!EvaluateInteger(E->getArg(0), Val, Info))
12096 return false;
12097
12098 unsigned N = Val.countr_zero();
12099 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12100 }
12101
12102 case Builtin::BI__builtin_fpclassify: {
12103 APFloat Val(0.0);
12104 if (!EvaluateFloat(E->getArg(5), Val, Info))
12105 return false;
12106 unsigned Arg;
12107 switch (Val.getCategory()) {
12108 case APFloat::fcNaN: Arg = 0; break;
12109 case APFloat::fcInfinity: Arg = 1; break;
12110 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12111 case APFloat::fcZero: Arg = 4; break;
12112 }
12113 return Visit(E->getArg(Arg));
12114 }
12115
12116 case Builtin::BI__builtin_isinf_sign: {
12117 APFloat Val(0.0);
12118 return EvaluateFloat(E->getArg(0), Val, Info) &&
12119 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12120 }
12121
12122 case Builtin::BI__builtin_isinf: {
12123 APFloat Val(0.0);
12124 return EvaluateFloat(E->getArg(0), Val, Info) &&
12125 Success(Val.isInfinity() ? 1 : 0, E);
12126 }
12127
12128 case Builtin::BI__builtin_isfinite: {
12129 APFloat Val(0.0);
12130 return EvaluateFloat(E->getArg(0), Val, Info) &&
12131 Success(Val.isFinite() ? 1 : 0, E);
12132 }
12133
12134 case Builtin::BI__builtin_isnan: {
12135 APFloat Val(0.0);
12136 return EvaluateFloat(E->getArg(0), Val, Info) &&
12137 Success(Val.isNaN() ? 1 : 0, E);
12138 }
12139
12140 case Builtin::BI__builtin_isnormal: {
12141 APFloat Val(0.0);
12142 return EvaluateFloat(E->getArg(0), Val, Info) &&
12143 Success(Val.isNormal() ? 1 : 0, E);
12144 }
12145
12146 case Builtin::BI__builtin_parity:
12147 case Builtin::BI__builtin_parityl:
12148 case Builtin::BI__builtin_parityll: {
12149 APSInt Val;
12150 if (!EvaluateInteger(E->getArg(0), Val, Info))
12151 return false;
12152
12153 return Success(Val.popcount() % 2, E);
12154 }
12155
12156 case Builtin::BI__builtin_popcount:
12157 case Builtin::BI__builtin_popcountl:
12158 case Builtin::BI__builtin_popcountll: {
12159 APSInt Val;
12160 if (!EvaluateInteger(E->getArg(0), Val, Info))
12161 return false;
12162
12163 return Success(Val.popcount(), E);
12164 }
12165
12166 case Builtin::BI__builtin_rotateleft8:
12167 case Builtin::BI__builtin_rotateleft16:
12168 case Builtin::BI__builtin_rotateleft32:
12169 case Builtin::BI__builtin_rotateleft64:
12170 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12171 case Builtin::BI_rotl16:
12172 case Builtin::BI_rotl:
12173 case Builtin::BI_lrotl:
12174 case Builtin::BI_rotl64: {
12175 APSInt Val, Amt;
12176 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12177 !EvaluateInteger(E->getArg(1), Amt, Info))
12178 return false;
12179
12180 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12181 }
12182
12183 case Builtin::BI__builtin_rotateright8:
12184 case Builtin::BI__builtin_rotateright16:
12185 case Builtin::BI__builtin_rotateright32:
12186 case Builtin::BI__builtin_rotateright64:
12187 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12188 case Builtin::BI_rotr16:
12189 case Builtin::BI_rotr:
12190 case Builtin::BI_lrotr:
12191 case Builtin::BI_rotr64: {
12192 APSInt Val, Amt;
12193 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12194 !EvaluateInteger(E->getArg(1), Amt, Info))
12195 return false;
12196
12197 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12198 }
12199
12200 case Builtin::BIstrlen:
12201 case Builtin::BIwcslen:
12202 // A call to strlen is not a constant expression.
12203 if (Info.getLangOpts().CPlusPlus11)
12204 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12205 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12206 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12207 else
12208 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12209 [[fallthrough]];
12210 case Builtin::BI__builtin_strlen:
12211 case Builtin::BI__builtin_wcslen: {
12212 // As an extension, we support __builtin_strlen() as a constant expression,
12213 // and support folding strlen() to a constant.
12214 uint64_t StrLen;
12215 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12216 return Success(StrLen, E);
12217 return false;
12218 }
12219
12220 case Builtin::BIstrcmp:
12221 case Builtin::BIwcscmp:
12222 case Builtin::BIstrncmp:
12223 case Builtin::BIwcsncmp:
12224 case Builtin::BImemcmp:
12225 case Builtin::BIbcmp:
12226 case Builtin::BIwmemcmp:
12227 // A call to strlen is not a constant expression.
12228 if (Info.getLangOpts().CPlusPlus11)
12229 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12230 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12231 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12232 else
12233 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12234 [[fallthrough]];
12235 case Builtin::BI__builtin_strcmp:
12236 case Builtin::BI__builtin_wcscmp:
12237 case Builtin::BI__builtin_strncmp:
12238 case Builtin::BI__builtin_wcsncmp:
12239 case Builtin::BI__builtin_memcmp:
12240 case Builtin::BI__builtin_bcmp:
12241 case Builtin::BI__builtin_wmemcmp: {
12242 LValue String1, String2;
12243 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12244 !EvaluatePointer(E->getArg(1), String2, Info))
12245 return false;
12246
12247 uint64_t MaxLength = uint64_t(-1);
12248 if (BuiltinOp != Builtin::BIstrcmp &&
12249 BuiltinOp != Builtin::BIwcscmp &&
12250 BuiltinOp != Builtin::BI__builtin_strcmp &&
12251 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12252 APSInt N;
12253 if (!EvaluateInteger(E->getArg(2), N, Info))
12254 return false;
12255 MaxLength = N.getExtValue();
12256 }
12257
12258 // Empty substrings compare equal by definition.
12259 if (MaxLength == 0u)
12260 return Success(0, E);
12261
12262 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12263 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12264 String1.Designator.Invalid || String2.Designator.Invalid)
12265 return false;
12266
12267 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12268 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12269
12270 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12271 BuiltinOp == Builtin::BIbcmp ||
12272 BuiltinOp == Builtin::BI__builtin_memcmp ||
12273 BuiltinOp == Builtin::BI__builtin_bcmp;
12274
12275 assert(IsRawByte ||(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType
( CharTy1, E->getArg(0)->getType()->getPointeeType()
) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2
))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "clang/lib/AST/ExprConstant.cpp", 12278, __extension__ __PRETTY_FUNCTION__
))
12276 (Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType
( CharTy1, E->getArg(0)->getType()->getPointeeType()
) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2
))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "clang/lib/AST/ExprConstant.cpp", 12278, __extension__ __PRETTY_FUNCTION__
))
12277 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType
( CharTy1, E->getArg(0)->getType()->getPointeeType()
) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2
))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "clang/lib/AST/ExprConstant.cpp", 12278, __extension__ __PRETTY_FUNCTION__
))
12278 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType
( CharTy1, E->getArg(0)->getType()->getPointeeType()
) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2
))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "clang/lib/AST/ExprConstant.cpp", 12278, __extension__ __PRETTY_FUNCTION__
))
;
12279
12280 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12281 // 'char8_t', but no other types.
12282 if (IsRawByte &&
12283 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12284 // FIXME: Consider using our bit_cast implementation to support this.
12285 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12286 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12287 << CharTy1 << CharTy2;
12288 return false;
12289 }
12290
12291 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12292 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12293 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12294 Char1.isInt() && Char2.isInt();
12295 };
12296 const auto &AdvanceElems = [&] {
12297 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12298 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12299 };
12300
12301 bool StopAtNull =
12302 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12303 BuiltinOp != Builtin::BIwmemcmp &&
12304 BuiltinOp != Builtin::BI__builtin_memcmp &&
12305 BuiltinOp != Builtin::BI__builtin_bcmp &&
12306 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12307 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12308 BuiltinOp == Builtin::BIwcsncmp ||
12309 BuiltinOp == Builtin::BIwmemcmp ||
12310 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12311 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12312 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12313
12314 for (; MaxLength; --MaxLength) {
12315 APValue Char1, Char2;
12316 if (!ReadCurElems(Char1, Char2))
12317 return false;
12318 if (Char1.getInt().ne(Char2.getInt())) {
12319 if (IsWide) // wmemcmp compares with wchar_t signedness.
12320 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12321 // memcmp always compares unsigned chars.
12322 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12323 }
12324 if (StopAtNull && !Char1.getInt())
12325 return Success(0, E);
12326 assert(!(StopAtNull && !Char2.getInt()))(static_cast <bool> (!(StopAtNull && !Char2.getInt
())) ? void (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())"
, "clang/lib/AST/ExprConstant.cpp", 12326, __extension__ __PRETTY_FUNCTION__
))
;
12327 if (!AdvanceElems())
12328 return false;
12329 }
12330 // We hit the strncmp / memcmp limit.
12331 return Success(0, E);
12332 }
12333
12334 case Builtin::BI__atomic_always_lock_free:
12335 case Builtin::BI__atomic_is_lock_free:
12336 case Builtin::BI__c11_atomic_is_lock_free: {
12337 APSInt SizeVal;
12338 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12339 return false;
12340
12341 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12342 // of two less than or equal to the maximum inline atomic width, we know it
12343 // is lock-free. If the size isn't a power of two, or greater than the
12344 // maximum alignment where we promote atomics, we know it is not lock-free
12345 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12346 // the answer can only be determined at runtime; for example, 16-byte
12347 // atomics have lock-free implementations on some, but not all,
12348 // x86-64 processors.
12349
12350 // Check power-of-two.
12351 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12352 if (Size.isPowerOfTwo()) {
12353 // Check against inlining width.
12354 unsigned InlineWidthBits =
12355 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12356 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12357 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12358 Size == CharUnits::One() ||
12359 E->getArg(1)->isNullPointerConstant(Info.Ctx,
12360 Expr::NPC_NeverValueDependent))
12361 // OK, we will inline appropriately-aligned operations of this size,
12362 // and _Atomic(T) is appropriately-aligned.
12363 return Success(1, E);
12364
12365 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12366 castAs<PointerType>()->getPointeeType();
12367 if (!PointeeType->isIncompleteType() &&
12368 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12369 // OK, we will inline operations on this object.
12370 return Success(1, E);
12371 }
12372 }
12373 }
12374
12375 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12376 Success(0, E) : Error(E);
12377 }
12378 case Builtin::BI__builtin_add_overflow:
12379 case Builtin::BI__builtin_sub_overflow:
12380 case Builtin::BI__builtin_mul_overflow:
12381 case Builtin::BI__builtin_sadd_overflow:
12382 case Builtin::BI__builtin_uadd_overflow:
12383 case Builtin::BI__builtin_uaddl_overflow:
12384 case Builtin::BI__builtin_uaddll_overflow:
12385 case Builtin::BI__builtin_usub_overflow:
12386 case Builtin::BI__builtin_usubl_overflow:
12387 case Builtin::BI__builtin_usubll_overflow:
12388 case Builtin::BI__builtin_umul_overflow:
12389 case Builtin::BI__builtin_umull_overflow:
12390 case Builtin::BI__builtin_umulll_overflow:
12391 case Builtin::BI__builtin_saddl_overflow:
12392 case Builtin::BI__builtin_saddll_overflow:
12393 case Builtin::BI__builtin_ssub_overflow:
12394 case Builtin::BI__builtin_ssubl_overflow:
12395 case Builtin::BI__builtin_ssubll_overflow:
12396 case Builtin::BI__builtin_smul_overflow:
12397 case Builtin::BI__builtin_smull_overflow:
12398 case Builtin::BI__builtin_smulll_overflow: {
12399 LValue ResultLValue;
12400 APSInt LHS, RHS;
12401
12402 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12403 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12404 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12405 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12406 return false;
12407
12408 APSInt Result;
12409 bool DidOverflow = false;
12410
12411 // If the types don't have to match, enlarge all 3 to the largest of them.
12412 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12413 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12414 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12415 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12416 ResultType->isSignedIntegerOrEnumerationType();
12417 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12418 ResultType->isSignedIntegerOrEnumerationType();
12419 uint64_t LHSSize = LHS.getBitWidth();
12420 uint64_t RHSSize = RHS.getBitWidth();
12421 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12422 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12423
12424 // Add an additional bit if the signedness isn't uniformly agreed to. We
12425 // could do this ONLY if there is a signed and an unsigned that both have
12426 // MaxBits, but the code to check that is pretty nasty. The issue will be
12427 // caught in the shrink-to-result later anyway.
12428 if (IsSigned && !AllSigned)
12429 ++MaxBits;
12430
12431 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12432 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12433 Result = APSInt(MaxBits, !IsSigned);
12434 }
12435
12436 // Find largest int.
12437 switch (BuiltinOp) {
12438 default:
12439 llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp"
, "clang/lib/AST/ExprConstant.cpp", 12439)
;
12440 case Builtin::BI__builtin_add_overflow:
12441 case Builtin::BI__builtin_sadd_overflow:
12442 case Builtin::BI__builtin_saddl_overflow:
12443 case Builtin::BI__builtin_saddll_overflow:
12444 case Builtin::BI__builtin_uadd_overflow:
12445 case Builtin::BI__builtin_uaddl_overflow:
12446 case Builtin::BI__builtin_uaddll_overflow:
12447 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12448 : LHS.uadd_ov(RHS, DidOverflow);
12449 break;
12450 case Builtin::BI__builtin_sub_overflow:
12451 case Builtin::BI__builtin_ssub_overflow:
12452 case Builtin::BI__builtin_ssubl_overflow:
12453 case Builtin::BI__builtin_ssubll_overflow:
12454 case Builtin::BI__builtin_usub_overflow:
12455 case Builtin::BI__builtin_usubl_overflow:
12456 case Builtin::BI__builtin_usubll_overflow:
12457 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12458 : LHS.usub_ov(RHS, DidOverflow);
12459 break;
12460 case Builtin::BI__builtin_mul_overflow:
12461 case Builtin::BI__builtin_smul_overflow:
12462 case Builtin::BI__builtin_smull_overflow:
12463 case Builtin::BI__builtin_smulll_overflow:
12464 case Builtin::BI__builtin_umul_overflow:
12465 case Builtin::BI__builtin_umull_overflow:
12466 case Builtin::BI__builtin_umulll_overflow:
12467 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12468 : LHS.umul_ov(RHS, DidOverflow);
12469 break;
12470 }
12471
12472 // In the case where multiple sizes are allowed, truncate and see if
12473 // the values are the same.
12474 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12475 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12476 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12477 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12478 // since it will give us the behavior of a TruncOrSelf in the case where
12479 // its parameter <= its size. We previously set Result to be at least the
12480 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12481 // will work exactly like TruncOrSelf.
12482 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12483 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12484
12485 if (!APSInt::isSameValue(Temp, Result))
12486 DidOverflow = true;
12487 Result = Temp;
12488 }
12489
12490 APValue APV{Result};
12491 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12492 return false;
12493 return Success(DidOverflow, E);
12494 }
12495 }
12496}
12497
12498/// Determine whether this is a pointer past the end of the complete
12499/// object referred to by the lvalue.
12500static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12501 const LValue &LV) {
12502 // A null pointer can be viewed as being "past the end" but we don't
12503 // choose to look at it that way here.
12504 if (!LV.getLValueBase())
12505 return false;
12506
12507 // If the designator is valid and refers to a subobject, we're not pointing
12508 // past the end.
12509 if (!LV.getLValueDesignator().Invalid &&
12510 !LV.getLValueDesignator().isOnePastTheEnd())
12511 return false;
12512
12513 // A pointer to an incomplete type might be past-the-end if the type's size is
12514 // zero. We cannot tell because the type is incomplete.
12515 QualType Ty = getType(LV.getLValueBase());
12516 if (Ty->isIncompleteType())
12517 return true;
12518
12519 // We're a past-the-end pointer if we point to the byte after the object,
12520 // no matter what our type or path is.
12521 auto Size = Ctx.getTypeSizeInChars(Ty);
12522 return LV.getLValueOffset() == Size;
12523}
12524
12525namespace {
12526
12527/// Data recursive integer evaluator of certain binary operators.
12528///
12529/// We use a data recursive algorithm for binary operators so that we are able
12530/// to handle extreme cases of chained binary operators without causing stack
12531/// overflow.
12532class DataRecursiveIntBinOpEvaluator {
12533 struct EvalResult {
12534 APValue Val;
12535 bool Failed;
12536
12537 EvalResult() : Failed(false) { }
12538
12539 void swap(EvalResult &RHS) {
12540 Val.swap(RHS.Val);
12541 Failed = RHS.Failed;
12542 RHS.Failed = false;
12543 }
12544 };
12545
12546 struct Job {
12547 const Expr *E;
12548 EvalResult LHSResult; // meaningful only for binary operator expression.
12549 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12550
12551 Job() = default;
12552 Job(Job &&) = default;
12553
12554 void startSpeculativeEval(EvalInfo &Info) {
12555 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12556 }
12557
12558 private:
12559 SpeculativeEvaluationRAII SpecEvalRAII;
12560 };
12561
12562 SmallVector<Job, 16> Queue;
12563
12564 IntExprEvaluator &IntEval;
12565 EvalInfo &Info;
12566 APValue &FinalResult;
12567
12568public:
12569 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12570 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12571
12572 /// True if \param E is a binary operator that we are going to handle
12573 /// data recursively.
12574 /// We handle binary operators that are comma, logical, or that have operands
12575 /// with integral or enumeration type.
12576 static bool shouldEnqueue(const BinaryOperator *E) {
12577 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12578 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12579 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12580 E->getRHS()->getType()->isIntegralOrEnumerationType());
12581 }
12582
12583 bool Traverse(const BinaryOperator *E) {
12584 enqueue(E);
12585 EvalResult PrevResult;
12586 while (!Queue.empty())
12587 process(PrevResult);
12588
12589 if (PrevResult.Failed) return false;
12590
12591 FinalResult.swap(PrevResult.Val);
12592 return true;
12593 }
12594
12595private:
12596 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12597 return IntEval.Success(Value, E, Result);
12598 }
12599 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12600 return IntEval.Success(Value, E, Result);
12601 }
12602 bool Error(const Expr *E) {
12603 return IntEval.Error(E);
12604 }
12605 bool Error(const Expr *E, diag::kind D) {
12606 return IntEval.Error(E, D);
12607 }
12608
12609 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12610 return Info.CCEDiag(E, D);
12611 }
12612
12613 // Returns true if visiting the RHS is necessary, false otherwise.
12614 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12615 bool &SuppressRHSDiags);
12616
12617 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12618 const BinaryOperator *E, APValue &Result);
12619
12620 void EvaluateExpr(const Expr *E, EvalResult &Result) {
12621 Result.Failed = !Evaluate(Result.Val, Info, E);
12622 if (Result.Failed)
12623 Result.Val = APValue();
12624 }
12625
12626 void process(EvalResult &Result);
12627
12628 void enqueue(const Expr *E) {
12629 E = E->IgnoreParens();
12630 Queue.resize(Queue.size()+1);
12631 Queue.back().E = E;
12632 Queue.back().Kind = Job::AnyExprKind;
12633 }
12634};
12635
12636}
12637
12638bool DataRecursiveIntBinOpEvaluator::
12639 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12640 bool &SuppressRHSDiags) {
12641 if (E->getOpcode() == BO_Comma) {
12642 // Ignore LHS but note if we could not evaluate it.
12643 if (LHSResult.Failed)
12644 return Info.noteSideEffect();
12645 return true;
12646 }
12647
12648 if (E->isLogicalOp()) {
12649 bool LHSAsBool;
12650 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12651 // We were able to evaluate the LHS, see if we can get away with not
12652 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12653 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12654 Success(LHSAsBool, E, LHSResult.Val);
12655 return false; // Ignore RHS
12656 }
12657 } else {
12658 LHSResult.Failed = true;
12659
12660 // Since we weren't able to evaluate the left hand side, it
12661 // might have had side effects.
12662 if (!Info.noteSideEffect())
12663 return false;
12664
12665 // We can't evaluate the LHS; however, sometimes the result
12666 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12667 // Don't ignore RHS and suppress diagnostics from this arm.
12668 SuppressRHSDiags = true;
12669 }
12670
12671 return true;
12672 }
12673
12674 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "clang/lib/AST/ExprConstant.cpp", 12675, __extension__ __PRETTY_FUNCTION__
))
12675 E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "clang/lib/AST/ExprConstant.cpp", 12675, __extension__ __PRETTY_FUNCTION__
))
;
12676
12677 if (LHSResult.Failed && !Info.noteFailure())
12678 return false; // Ignore RHS;
12679
12680 return true;
12681}
12682
12683static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12684 bool IsSub) {
12685 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12686 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12687 // offsets.
12688 assert(!LVal.hasLValuePath() && "have designator for integer lvalue")(static_cast <bool> (!LVal.hasLValuePath() && "have designator for integer lvalue"
) ? void (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 12688, __extension__ __PRETTY_FUNCTION__
))
;
12689 CharUnits &Offset = LVal.getLValueOffset();
12690 uint64_t Offset64 = Offset.getQuantity();
12691 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12692 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12693 : Offset64 + Index64);
12694}
12695
12696bool DataRecursiveIntBinOpEvaluator::
12697 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12698 const BinaryOperator *E, APValue &Result) {
12699 if (E->getOpcode() == BO_Comma) {
12700 if (RHSResult.Failed)
12701 return false;
12702 Result = RHSResult.Val;
12703 return true;
12704 }
12705
12706 if (E->isLogicalOp()) {
12707 bool lhsResult, rhsResult;
12708 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12709 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12710
12711 if (LHSIsOK) {
12712 if (RHSIsOK) {
12713 if (E->getOpcode() == BO_LOr)
12714 return Success(lhsResult || rhsResult, E, Result);
12715 else
12716 return Success(lhsResult && rhsResult, E, Result);
12717 }
12718 } else {
12719 if (RHSIsOK) {
12720 // We can't evaluate the LHS; however, sometimes the result
12721 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12722 if (rhsResult == (E->getOpcode() == BO_LOr))
12723 return Success(rhsResult, E, Result);
12724 }
12725 }
12726
12727 return false;
12728 }
12729
12730 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "clang/lib/AST/ExprConstant.cpp", 12731, __extension__ __PRETTY_FUNCTION__
))
12731 E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "clang/lib/AST/ExprConstant.cpp", 12731, __extension__ __PRETTY_FUNCTION__
))
;
12732
12733 if (LHSResult.Failed || RHSResult.Failed)
12734 return false;
12735
12736 const APValue &LHSVal = LHSResult.Val;
12737 const APValue &RHSVal = RHSResult.Val;
12738
12739 // Handle cases like (unsigned long)&a + 4.
12740 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12741 Result = LHSVal;
12742 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12743 return true;
12744 }
12745
12746 // Handle cases like 4 + (unsigned long)&a
12747 if (E->getOpcode() == BO_Add &&
12748 RHSVal.isLValue() && LHSVal.isInt()) {
12749 Result = RHSVal;
12750 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12751 return true;
12752 }
12753
12754 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12755 // Handle (intptr_t)&&A - (intptr_t)&&B.
12756 if (!LHSVal.getLValueOffset().isZero() ||
12757 !RHSVal.getLValueOffset().isZero())
12758 return false;
12759 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12760 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12761 if (!LHSExpr || !RHSExpr)
12762 return false;
12763 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12764 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12765 if (!LHSAddrExpr || !RHSAddrExpr)
12766 return false;
12767 // Make sure both labels come from the same function.
12768 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12769 RHSAddrExpr->getLabel()->getDeclContext())
12770 return false;
12771 Result = APValue(LHSAddrExpr, RHSAddrExpr);
12772 return true;
12773 }
12774
12775 // All the remaining cases expect both operands to be an integer
12776 if (!LHSVal.isInt() || !RHSVal.isInt())
12777 return Error(E);
12778
12779 // Set up the width and signedness manually, in case it can't be deduced
12780 // from the operation we're performing.
12781 // FIXME: Don't do this in the cases where we can deduce it.
12782 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12783 E->getType()->isUnsignedIntegerOrEnumerationType());
12784 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12785 RHSVal.getInt(), Value))
12786 return false;
12787 return Success(Value, E, Result);
12788}
12789
12790void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12791 Job &job = Queue.back();
12792
12793 switch (job.Kind) {
12794 case Job::AnyExprKind: {
12795 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12796 if (shouldEnqueue(Bop)) {
12797 job.Kind = Job::BinOpKind;
12798 enqueue(Bop->getLHS());
12799 return;
12800 }
12801 }
12802
12803 EvaluateExpr(job.E, Result);
12804 Queue.pop_back();
12805 return;
12806 }
12807
12808 case Job::BinOpKind: {
12809 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12810 bool SuppressRHSDiags = false;
12811 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12812 Queue.pop_back();
12813 return;
12814 }
12815 if (SuppressRHSDiags)
12816 job.startSpeculativeEval(Info);
12817 job.LHSResult.swap(Result);
12818 job.Kind = Job::BinOpVisitedLHSKind;
12819 enqueue(Bop->getRHS());
12820 return;
12821 }
12822
12823 case Job::BinOpVisitedLHSKind: {
12824 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12825 EvalResult RHS;
12826 RHS.swap(Result);
12827 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12828 Queue.pop_back();
12829 return;
12830 }
12831 }
12832
12833 llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "clang/lib/AST/ExprConstant.cpp"
, 12833)
;
12834}
12835
12836namespace {
12837enum class CmpResult {
12838 Unequal,
12839 Less,
12840 Equal,
12841 Greater,
12842 Unordered,
12843};
12844}
12845
12846template <class SuccessCB, class AfterCB>
12847static bool
12848EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12849 SuccessCB &&Success, AfterCB &&DoAfter) {
12850 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 12850, __extension__ __PRETTY_FUNCTION__))
;
12851 assert(E->isComparisonOp() && "expected comparison operator")(static_cast <bool> (E->isComparisonOp() && "expected comparison operator"
) ? void (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\""
, "clang/lib/AST/ExprConstant.cpp", 12851, __extension__ __PRETTY_FUNCTION__
))
;
12852 assert((E->getOpcode() == BO_Cmp ||(static_cast <bool> ((E->getOpcode() == BO_Cmp || E->
getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation"
) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "clang/lib/AST/ExprConstant.cpp", 12854, __extension__ __PRETTY_FUNCTION__
))
12853 E->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((E->getOpcode() == BO_Cmp || E->
getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation"
) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "clang/lib/AST/ExprConstant.cpp", 12854, __extension__ __PRETTY_FUNCTION__
))
12854 "unsupported binary expression evaluation")(static_cast <bool> ((E->getOpcode() == BO_Cmp || E->
getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation"
) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "clang/lib/AST/ExprConstant.cpp", 12854, __extension__ __PRETTY_FUNCTION__
))
;
12855 auto Error = [&](const Expr *E) {
12856 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12857 return false;
12858 };
12859
12860 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12861 bool IsEquality = E->isEqualityOp();
12862
12863 QualType LHSTy = E->getLHS()->getType();
12864 QualType RHSTy = E->getRHS()->getType();
12865
12866 if (LHSTy->isIntegralOrEnumerationType() &&
12867 RHSTy->isIntegralOrEnumerationType()) {
12868 APSInt LHS, RHS;
12869 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12870 if (!LHSOK && !Info.noteFailure())
12871 return false;
12872 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12873 return false;
12874 if (LHS < RHS)
12875 return Success(CmpResult::Less, E);
12876 if (LHS > RHS)
12877 return Success(CmpResult::Greater, E);
12878 return Success(CmpResult::Equal, E);
12879 }
12880
12881 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12882 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12883 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12884
12885 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12886 if (!LHSOK && !Info.noteFailure())
12887 return false;
12888 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12889 return false;
12890 if (LHSFX < RHSFX)
12891 return Success(CmpResult::Less, E);
12892 if (LHSFX > RHSFX)
12893 return Success(CmpResult::Greater, E);
12894 return Success(CmpResult::Equal, E);
12895 }
12896
12897 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12898 ComplexValue LHS, RHS;
12899 bool LHSOK;
12900 if (E->isAssignmentOp()) {
12901 LValue LV;
12902 EvaluateLValue(E->getLHS(), LV, Info);
12903 LHSOK = false;
12904 } else if (LHSTy->isRealFloatingType()) {
12905 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12906 if (LHSOK) {
12907 LHS.makeComplexFloat();
12908 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12909 }
12910 } else {
12911 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12912 }
12913 if (!LHSOK && !Info.noteFailure())
12914 return false;
12915
12916 if (E->getRHS()->getType()->isRealFloatingType()) {
12917 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12918 return false;
12919 RHS.makeComplexFloat();
12920 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12921 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12922 return false;
12923
12924 if (LHS.isComplexFloat()) {
12925 APFloat::cmpResult CR_r =
12926 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12927 APFloat::cmpResult CR_i =
12928 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12929 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12930 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12931 } else {
12932 assert(IsEquality && "invalid complex comparison")(static_cast <bool> (IsEquality && "invalid complex comparison"
) ? void (0) : __assert_fail ("IsEquality && \"invalid complex comparison\""
, "clang/lib/AST/ExprConstant.cpp", 12932, __extension__ __PRETTY_FUNCTION__
))
;
12933 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12934 LHS.getComplexIntImag() == RHS.getComplexIntImag();
12935 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12936 }
12937 }
12938
12939 if (LHSTy->isRealFloatingType() &&
12940 RHSTy->isRealFloatingType()) {
12941 APFloat RHS(0.0), LHS(0.0);
12942
12943 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12944 if (!LHSOK && !Info.noteFailure())
12945 return false;
12946
12947 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12948 return false;
12949
12950 assert(E->isComparisonOp() && "Invalid binary operator!")(static_cast <bool> (E->isComparisonOp() && "Invalid binary operator!"
) ? void (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\""
, "clang/lib/AST/ExprConstant.cpp", 12950, __extension__ __PRETTY_FUNCTION__
))
;
12951 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12952 if (!Info.InConstantContext &&
12953 APFloatCmpResult == APFloat::cmpUnordered &&
12954 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12955 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12956 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12957 return false;
12958 }
12959 auto GetCmpRes = [&]() {
12960 switch (APFloatCmpResult) {
12961 case APFloat::cmpEqual:
12962 return CmpResult::Equal;
12963 case APFloat::cmpLessThan:
12964 return CmpResult::Less;
12965 case APFloat::cmpGreaterThan:
12966 return CmpResult::Greater;
12967 case APFloat::cmpUnordered:
12968 return CmpResult::Unordered;
12969 }
12970 llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum"
, "clang/lib/AST/ExprConstant.cpp", 12970)
;
12971 };
12972 return Success(GetCmpRes(), E);
12973 }
12974
12975 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12976 LValue LHSValue, RHSValue;
12977
12978 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12979 if (!LHSOK && !Info.noteFailure())
12980 return false;
12981
12982 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12983 return false;
12984
12985 // Reject differing bases from the normal codepath; we special-case
12986 // comparisons to null.
12987 if (!HasSameBase(LHSValue, RHSValue)) {
12988 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
12989 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
12990 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
12991 Info.FFDiag(E, DiagID)
12992 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
12993 return false;
12994 };
12995 // Inequalities and subtractions between unrelated pointers have
12996 // unspecified or undefined behavior.
12997 if (!IsEquality)
12998 return DiagComparison(
12999 diag::note_constexpr_pointer_comparison_unspecified);
13000 // A constant address may compare equal to the address of a symbol.
13001 // The one exception is that address of an object cannot compare equal
13002 // to a null pointer constant.
13003 // TODO: Should we restrict this to actual null pointers, and exclude the
13004 // case of zero cast to pointer type?
13005 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13006 (!RHSValue.Base && !RHSValue.Offset.isZero()))
13007 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13008 !RHSValue.Base);
13009 // It's implementation-defined whether distinct literals will have
13010 // distinct addresses. In clang, the result of such a comparison is
13011 // unspecified, so it is not a constant expression. However, we do know
13012 // that the address of a literal will be non-null.
13013 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13014 LHSValue.Base && RHSValue.Base)
13015 return DiagComparison(diag::note_constexpr_literal_comparison);
13016 // We can't tell whether weak symbols will end up pointing to the same
13017 // object.
13018 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13019 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13020 !IsWeakLValue(LHSValue));
13021 // We can't compare the address of the start of one object with the
13022 // past-the-end address of another object, per C++ DR1652.
13023 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13024 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13025 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13026 true);
13027 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13028 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13029 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13030 false);
13031 // We can't tell whether an object is at the same address as another
13032 // zero sized object.
13033 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13034 (LHSValue.Base && isZeroSized(RHSValue)))
13035 return DiagComparison(
13036 diag::note_constexpr_pointer_comparison_zero_sized);
13037 return Success(CmpResult::Unequal, E);
13038 }
13039
13040 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13041 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13042
13043 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13044 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13045
13046 // C++11 [expr.rel]p3:
13047 // Pointers to void (after pointer conversions) can be compared, with a
13048 // result defined as follows: If both pointers represent the same
13049 // address or are both the null pointer value, the result is true if the
13050 // operator is <= or >= and false otherwise; otherwise the result is
13051 // unspecified.
13052 // We interpret this as applying to pointers to *cv* void.
13053 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13054 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13055
13056 // C++11 [expr.rel]p2:
13057 // - If two pointers point to non-static data members of the same object,
13058 // or to subobjects or array elements fo such members, recursively, the
13059 // pointer to the later declared member compares greater provided the
13060 // two members have the same access control and provided their class is
13061 // not a union.
13062 // [...]
13063 // - Otherwise pointer comparisons are unspecified.
13064 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13065 bool WasArrayIndex;
13066 unsigned Mismatch = FindDesignatorMismatch(
13067 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13068 // At the point where the designators diverge, the comparison has a
13069 // specified value if:
13070 // - we are comparing array indices
13071 // - we are comparing fields of a union, or fields with the same access
13072 // Otherwise, the result is unspecified and thus the comparison is not a
13073 // constant expression.
13074 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13075 Mismatch < RHSDesignator.Entries.size()) {
13076 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13077 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13078 if (!LF && !RF)
13079 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13080 else if (!LF)
13081 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13082 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13083 << RF->getParent() << RF;
13084 else if (!RF)
13085 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13086 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13087 << LF->getParent() << LF;
13088 else if (!LF->getParent()->isUnion() &&
13089 LF->getAccess() != RF->getAccess())
13090 Info.CCEDiag(E,
13091 diag::note_constexpr_pointer_comparison_differing_access)
13092 << LF << LF->getAccess() << RF << RF->getAccess()
13093 << LF->getParent();
13094 }
13095 }
13096
13097 // The comparison here must be unsigned, and performed with the same
13098 // width as the pointer.
13099 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13100 uint64_t CompareLHS = LHSOffset.getQuantity();
13101 uint64_t CompareRHS = RHSOffset.getQuantity();
13102 assert(PtrSize <= 64 && "Unexpected pointer width")(static_cast <bool> (PtrSize <= 64 && "Unexpected pointer width"
) ? void (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\""
, "clang/lib/AST/ExprConstant.cpp", 13102, __extension__ __PRETTY_FUNCTION__
))
;
13103 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13104 CompareLHS &= Mask;
13105 CompareRHS &= Mask;
13106
13107 // If there is a base and this is a relational operator, we can only
13108 // compare pointers within the object in question; otherwise, the result
13109 // depends on where the object is located in memory.
13110 if (!LHSValue.Base.isNull() && IsRelational) {
13111 QualType BaseTy = getType(LHSValue.Base);
13112 if (BaseTy->isIncompleteType())
13113 return Error(E);
13114 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13115 uint64_t OffsetLimit = Size.getQuantity();
13116 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13117 return Error(E);
13118 }
13119
13120 if (CompareLHS < CompareRHS)
13121 return Success(CmpResult::Less, E);
13122 if (CompareLHS > CompareRHS)
13123 return Success(CmpResult::Greater, E);
13124 return Success(CmpResult::Equal, E);
13125 }
13126
13127 if (LHSTy->isMemberPointerType()) {
13128 assert(IsEquality && "unexpected member pointer operation")(static_cast <bool> (IsEquality && "unexpected member pointer operation"
) ? void (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\""
, "clang/lib/AST/ExprConstant.cpp", 13128, __extension__ __PRETTY_FUNCTION__
))
;
13129 assert(RHSTy->isMemberPointerType() && "invalid comparison")(static_cast <bool> (RHSTy->isMemberPointerType() &&
"invalid comparison") ? void (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\""
, "clang/lib/AST/ExprConstant.cpp", 13129, __extension__ __PRETTY_FUNCTION__
))
;
13130
13131 MemberPtr LHSValue, RHSValue;
13132
13133 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13134 if (!LHSOK && !Info.noteFailure())
13135 return false;
13136
13137 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13138 return false;
13139
13140 // If either operand is a pointer to a weak function, the comparison is not
13141 // constant.
13142 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13143 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13144 << LHSValue.getDecl();
13145 return false;
13146 }
13147 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13148 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13149 << RHSValue.getDecl();
13150 return false;
13151 }
13152
13153 // C++11 [expr.eq]p2:
13154 // If both operands are null, they compare equal. Otherwise if only one is
13155 // null, they compare unequal.
13156 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13157 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13158 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13159 }
13160
13161 // Otherwise if either is a pointer to a virtual member function, the
13162 // result is unspecified.
13163 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13164 if (MD->isVirtual())
13165 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13166 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13167 if (MD->isVirtual())
13168 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13169
13170 // Otherwise they compare equal if and only if they would refer to the
13171 // same member of the same most derived object or the same subobject if
13172 // they were dereferenced with a hypothetical object of the associated
13173 // class type.
13174 bool Equal = LHSValue == RHSValue;
13175 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13176 }
13177
13178 if (LHSTy->isNullPtrType()) {
13179 assert(E->isComparisonOp() && "unexpected nullptr operation")(static_cast <bool> (E->isComparisonOp() && "unexpected nullptr operation"
) ? void (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\""
, "clang/lib/AST/ExprConstant.cpp", 13179, __extension__ __PRETTY_FUNCTION__
))
;
13180 assert(RHSTy->isNullPtrType() && "missing pointer conversion")(static_cast <bool> (RHSTy->isNullPtrType() &&
"missing pointer conversion") ? void (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\""
, "clang/lib/AST/ExprConstant.cpp", 13180, __extension__ __PRETTY_FUNCTION__
))
;
13181 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13182 // are compared, the result is true of the operator is <=, >= or ==, and
13183 // false otherwise.
13184 return Success(CmpResult::Equal, E);
13185 }
13186
13187 return DoAfter();
13188}
13189
13190bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13191 if (!CheckLiteralType(Info, E))
13192 return false;
13193
13194 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13195 ComparisonCategoryResult CCR;
13196 switch (CR) {
13197 case CmpResult::Unequal:
13198 llvm_unreachable("should never produce Unequal for three-way comparison")::llvm::llvm_unreachable_internal("should never produce Unequal for three-way comparison"
, "clang/lib/AST/ExprConstant.cpp", 13198)
;
13199 case CmpResult::Less:
13200 CCR = ComparisonCategoryResult::Less;
13201 break;
13202 case CmpResult::Equal:
13203 CCR = ComparisonCategoryResult::Equal;
13204 break;
13205 case CmpResult::Greater:
13206 CCR = ComparisonCategoryResult::Greater;
13207 break;
13208 case CmpResult::Unordered:
13209 CCR = ComparisonCategoryResult::Unordered;
13210 break;
13211 }
13212 // Evaluation succeeded. Lookup the information for the comparison category
13213 // type and fetch the VarDecl for the result.
13214 const ComparisonCategoryInfo &CmpInfo =
13215 Info.Ctx.CompCategories.getInfoForType(E->getType());
13216 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13217 // Check and evaluate the result as a constant expression.
13218 LValue LV;
13219 LV.set(VD);
13220 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13221 return false;
13222 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13223 ConstantExprKind::Normal);
13224 };
13225 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13226 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13227 });
13228}
13229
13230bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13231 const CXXParenListInitExpr *E) {
13232 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13233}
13234
13235bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13236 // We don't support assignment in C. C++ assignments don't get here because
13237 // assignment is an lvalue in C++.
13238 if (E->isAssignmentOp()) {
13239 Error(E);
13240 if (!Info.noteFailure())
13241 return false;
13242 }
13243
13244 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13245 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13246
13247 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(static_cast <bool> ((!E->getLHS()->getType()->
isIntegralOrEnumerationType() || !E->getRHS()->getType(
)->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "clang/lib/AST/ExprConstant.cpp", 13249, __extension__ __PRETTY_FUNCTION__
))
13248 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((!E->getLHS()->getType()->
isIntegralOrEnumerationType() || !E->getRHS()->getType(
)->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "clang/lib/AST/ExprConstant.cpp", 13249, __extension__ __PRETTY_FUNCTION__
))
13249 "DataRecursiveIntBinOpEvaluator should have handled integral types")(static_cast <bool> ((!E->getLHS()->getType()->
isIntegralOrEnumerationType() || !E->getRHS()->getType(
)->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "clang/lib/AST/ExprConstant.cpp", 13249, __extension__ __PRETTY_FUNCTION__
))
;
13250
13251 if (E->isComparisonOp()) {
13252 // Evaluate builtin binary comparisons by evaluating them as three-way
13253 // comparisons and then translating the result.
13254 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13255 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&(static_cast <bool> ((CR != CmpResult::Unequal || E->
isEqualityOp()) && "should only produce Unequal for equality comparisons"
) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\""
, "clang/lib/AST/ExprConstant.cpp", 13256, __extension__ __PRETTY_FUNCTION__
))
13256 "should only produce Unequal for equality comparisons")(static_cast <bool> ((CR != CmpResult::Unequal || E->
isEqualityOp()) && "should only produce Unequal for equality comparisons"
) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\""
, "clang/lib/AST/ExprConstant.cpp", 13256, __extension__ __PRETTY_FUNCTION__
))
;
13257 bool IsEqual = CR == CmpResult::Equal,
13258 IsLess = CR == CmpResult::Less,
13259 IsGreater = CR == CmpResult::Greater;
13260 auto Op = E->getOpcode();
13261 switch (Op) {
13262 default:
13263 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "clang/lib/AST/ExprConstant.cpp", 13263)
;
13264 case BO_EQ:
13265 case BO_NE:
13266 return Success(IsEqual == (Op == BO_EQ), E);
13267 case BO_LT:
13268 return Success(IsLess, E);
13269 case BO_GT:
13270 return Success(IsGreater, E);
13271 case BO_LE:
13272 return Success(IsEqual || IsLess, E);
13273 case BO_GE:
13274 return Success(IsEqual || IsGreater, E);
13275 }
13276 };
13277 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13278 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13279 });
13280 }
13281
13282 QualType LHSTy = E->getLHS()->getType();
13283 QualType RHSTy = E->getRHS()->getType();
13284
13285 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13286 E->getOpcode() == BO_Sub) {
13287 LValue LHSValue, RHSValue;
13288
13289 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13290 if (!LHSOK && !Info.noteFailure())
13291 return false;
13292
13293 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13294 return false;
13295
13296 // Reject differing bases from the normal codepath; we special-case
13297 // comparisons to null.
13298 if (!HasSameBase(LHSValue, RHSValue)) {
13299 // Handle &&A - &&B.
13300 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13301 return Error(E);
13302 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13303 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13304 if (!LHSExpr || !RHSExpr)
13305 return Error(E);
13306 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13307 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13308 if (!LHSAddrExpr || !RHSAddrExpr)
13309 return Error(E);
13310 // Make sure both labels come from the same function.
13311 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13312 RHSAddrExpr->getLabel()->getDeclContext())
13313 return Error(E);
13314 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13315 }
13316 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13317 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13318
13319 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13320 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13321
13322 // C++11 [expr.add]p6:
13323 // Unless both pointers point to elements of the same array object, or
13324 // one past the last element of the array object, the behavior is
13325 // undefined.
13326 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13327 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13328 RHSDesignator))
13329 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13330
13331 QualType Type = E->getLHS()->getType();
13332 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13333
13334 CharUnits ElementSize;
13335 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13336 return false;
13337
13338 // As an extension, a type may have zero size (empty struct or union in
13339 // C, array of zero length). Pointer subtraction in such cases has
13340 // undefined behavior, so is not constant.
13341 if (ElementSize.isZero()) {
13342 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13343 << ElementType;
13344 return false;
13345 }
13346
13347 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13348 // and produce incorrect results when it overflows. Such behavior
13349 // appears to be non-conforming, but is common, so perhaps we should
13350 // assume the standard intended for such cases to be undefined behavior
13351 // and check for them.
13352
13353 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13354 // overflow in the final conversion to ptrdiff_t.
13355 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13356 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13357 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13358 false);
13359 APSInt TrueResult = (LHS - RHS) / ElemSize;
13360 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13361
13362 if (Result.extend(65) != TrueResult &&
13363 !HandleOverflow(Info, E, TrueResult, E->getType()))
13364 return false;
13365 return Success(Result, E);
13366 }
13367
13368 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13369}
13370
13371/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13372/// a result as the expression's type.
13373bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13374 const UnaryExprOrTypeTraitExpr *E) {
13375 switch(E->getKind()) {
13376 case UETT_PreferredAlignOf:
13377 case UETT_AlignOf: {
13378 if (E->isArgumentType())
13379 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13380 E);
13381 else
13382 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13383 E);
13384 }
13385
13386 case UETT_VecStep: {
13387 QualType Ty = E->getTypeOfArgument();
13388
13389 if (Ty->isVectorType()) {
13390 unsigned n = Ty->castAs<VectorType>()->getNumElements();
13391
13392 // The vec_step built-in functions that take a 3-component
13393 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13394 if (n == 3)
13395 n = 4;
13396
13397 return Success(n, E);
13398 } else
13399 return Success(1, E);
13400 }
13401
13402 case UETT_SizeOf: {
13403 QualType SrcTy = E->getTypeOfArgument();
13404 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13405 // the result is the size of the referenced type."
13406 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13407 SrcTy = Ref->getPointeeType();
13408
13409 CharUnits Sizeof;
13410 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13411 return false;
13412 return Success(Sizeof, E);
13413 }
13414 case UETT_OpenMPRequiredSimdAlign:
13415 assert(E->isArgumentType())(static_cast <bool> (E->isArgumentType()) ? void (0)
: __assert_fail ("E->isArgumentType()", "clang/lib/AST/ExprConstant.cpp"
, 13415, __extension__ __PRETTY_FUNCTION__))
;
13416 return Success(
13417 Info.Ctx.toCharUnitsFromBits(
13418 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13419 .getQuantity(),
13420 E);
13421 }
13422
13423 llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "clang/lib/AST/ExprConstant.cpp"
, 13423)
;
13424}
13425
13426bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13427 CharUnits Result;
13428 unsigned n = OOE->getNumComponents();
13429 if (n == 0)
13430 return Error(OOE);
13431 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13432 for (unsigned i = 0; i != n; ++i) {
13433 OffsetOfNode ON = OOE->getComponent(i);
13434 switch (ON.getKind()) {
13435 case OffsetOfNode::Array: {
13436 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13437 APSInt IdxResult;
13438 if (!EvaluateInteger(Idx, IdxResult, Info))
13439 return false;
13440 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13441 if (!AT)
13442 return Error(OOE);
13443 CurrentType = AT->getElementType();
13444 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13445 Result += IdxResult.getSExtValue() * ElementSize;
13446 break;
13447 }
13448
13449 case OffsetOfNode::Field: {
13450 FieldDecl *MemberDecl = ON.getField();
13451 const RecordType *RT = CurrentType->getAs<RecordType>();
13452 if (!RT)
13453 return Error(OOE);
13454 RecordDecl *RD = RT->getDecl();
13455 if (RD->isInvalidDecl()) return false;
13456 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13457 unsigned i = MemberDecl->getFieldIndex();
13458 assert(i < RL.getFieldCount() && "offsetof field in wrong type")(static_cast <bool> (i < RL.getFieldCount() &&
"offsetof field in wrong type") ? void (0) : __assert_fail (
"i < RL.getFieldCount() && \"offsetof field in wrong type\""
, "clang/lib/AST/ExprConstant.cpp", 13458, __extension__ __PRETTY_FUNCTION__
))
;
13459 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13460 CurrentType = MemberDecl->getType().getNonReferenceType();
13461 break;
13462 }
13463
13464 case OffsetOfNode::Identifier:
13465 llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof"
, "clang/lib/AST/ExprConstant.cpp", 13465)
;
13466
13467 case OffsetOfNode::Base: {
13468 CXXBaseSpecifier *BaseSpec = ON.getBase();
13469 if (BaseSpec->isVirtual())
13470 return Error(OOE);
13471
13472 // Find the layout of the class whose base we are looking into.
13473 const RecordType *RT = CurrentType->getAs<RecordType>();
13474 if (!RT)
13475 return Error(OOE);
13476 RecordDecl *RD = RT->getDecl();
13477 if (RD->isInvalidDecl()) return false;
13478 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13479
13480 // Find the base class itself.
13481 CurrentType = BaseSpec->getType();
13482 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13483 if (!BaseRT)
13484 return Error(OOE);
13485
13486 // Add the offset to the base.
13487 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13488 break;
13489 }
13490 }
13491 }
13492 return Success(Result, OOE);
13493}
13494
13495bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13496 switch (E->getOpcode()) {
13497 default:
13498 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13499 // See C99 6.6p3.
13500 return Error(E);
13501 case UO_Extension:
13502 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13503 // If so, we could clear the diagnostic ID.
13504 return Visit(E->getSubExpr());
13505 case UO_Plus:
13506 // The result is just the value.
13507 return Visit(E->getSubExpr());
13508 case UO_Minus: {
13509 if (!Visit(E->getSubExpr()))
13510 return false;
13511 if (!Result.isInt()) return Error(E);
13512 const APSInt &Value = Result.getInt();
13513 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
13514 if (Info.checkingForUndefinedBehavior())
13515 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13516 diag::warn_integer_constant_overflow)
13517 << toString(Value, 10) << E->getType();
13518
13519 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13520 E->getType()))
13521 return false;
13522 }
13523 return Success(-Value, E);
13524 }
13525 case UO_Not: {
13526 if (!Visit(E->getSubExpr()))
13527 return false;
13528 if (!Result.isInt()) return Error(E);
13529 return Success(~Result.getInt(), E);
13530 }
13531 case UO_LNot: {
13532 bool bres;
13533 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13534 return false;
13535 return Success(!bres, E);
13536 }
13537 }
13538}
13539
13540/// HandleCast - This is used to evaluate implicit or explicit casts where the
13541/// result type is integer.
13542bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13543 const Expr *SubExpr = E->getSubExpr();
13544 QualType DestType = E->getType();
13545 QualType SrcType = SubExpr->getType();
13546
13547 switch (E->getCastKind()) {
13548 case CK_BaseToDerived:
13549 case CK_DerivedToBase:
13550 case CK_UncheckedDerivedToBase:
13551 case CK_Dynamic:
13552 case CK_ToUnion:
13553 case CK_ArrayToPointerDecay:
13554 case CK_FunctionToPointerDecay:
13555 case CK_NullToPointer:
13556 case CK_NullToMemberPointer:
13557 case CK_BaseToDerivedMemberPointer:
13558 case CK_DerivedToBaseMemberPointer:
13559 case CK_ReinterpretMemberPointer:
13560 case CK_ConstructorConversion:
13561 case CK_IntegralToPointer:
13562 case CK_ToVoid:
13563 case CK_VectorSplat:
13564 case CK_IntegralToFloating:
13565 case CK_FloatingCast:
13566 case CK_CPointerToObjCPointerCast:
13567 case CK_BlockPointerToObjCPointerCast:
13568 case CK_AnyPointerToBlockPointerCast:
13569 case CK_ObjCObjectLValueCast:
13570 case CK_FloatingRealToComplex:
13571 case CK_FloatingComplexToReal:
13572 case CK_FloatingComplexCast:
13573 case CK_FloatingComplexToIntegralComplex:
13574 case CK_IntegralRealToComplex:
13575 case CK_IntegralComplexCast:
13576 case CK_IntegralComplexToFloatingComplex:
13577 case CK_BuiltinFnToFnPtr:
13578 case CK_ZeroToOCLOpaqueType:
13579 case CK_NonAtomicToAtomic:
13580 case CK_AddressSpaceConversion:
13581 case CK_IntToOCLSampler:
13582 case CK_FloatingToFixedPoint:
13583 case CK_FixedPointToFloating:
13584 case CK_FixedPointCast:
13585 case CK_IntegralToFixedPoint:
13586 case CK_MatrixCast:
13587 llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value"
, "clang/lib/AST/ExprConstant.cpp", 13587)
;
13588
13589 case CK_BitCast:
13590 case CK_Dependent:
13591 case CK_LValueBitCast:
13592 case CK_ARCProduceObject:
13593 case CK_ARCConsumeObject:
13594 case CK_ARCReclaimReturnedObject:
13595 case CK_ARCExtendBlockObject:
13596 case CK_CopyAndAutoreleaseBlockObject:
13597 return Error(E);
13598
13599 case CK_UserDefinedConversion:
13600 case CK_LValueToRValue:
13601 case CK_AtomicToNonAtomic:
13602 case CK_NoOp:
13603 case CK_LValueToRValueBitCast:
13604 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13605
13606 case CK_MemberPointerToBoolean:
13607 case CK_PointerToBoolean:
13608 case CK_IntegralToBoolean:
13609 case CK_FloatingToBoolean:
13610 case CK_BooleanToSignedIntegral:
13611 case CK_FloatingComplexToBoolean:
13612 case CK_IntegralComplexToBoolean: {
13613 bool BoolResult;
13614 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13615 return false;
13616 uint64_t IntResult = BoolResult;
13617 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13618 IntResult = (uint64_t)-1;
13619 return Success(IntResult, E);
13620 }
13621
13622 case CK_FixedPointToIntegral: {
13623 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13624 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13625 return false;
13626 bool Overflowed;
13627 llvm::APSInt Result = Src.convertToInt(
13628 Info.Ctx.getIntWidth(DestType),
13629 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13630 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13631 return false;
13632 return Success(Result, E);
13633 }
13634
13635 case CK_FixedPointToBoolean: {
13636 // Unsigned padding does not affect this.
13637 APValue Val;
13638 if (!Evaluate(Val, Info, SubExpr))
13639 return false;
13640 return Success(Val.getFixedPoint().getBoolValue(), E);
13641 }
13642
13643 case CK_IntegralCast: {
13644 if (!Visit(SubExpr))
13645 return false;
13646
13647 if (!Result.isInt()) {
13648 // Allow casts of address-of-label differences if they are no-ops
13649 // or narrowing. (The narrowing case isn't actually guaranteed to
13650 // be constant-evaluatable except in some narrow cases which are hard
13651 // to detect here. We let it through on the assumption the user knows
13652 // what they are doing.)
13653 if (Result.isAddrLabelDiff())
13654 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13655 // Only allow casts of lvalues if they are lossless.
13656 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13657 }
13658
13659 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13660 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13661 DestType->isEnumeralType()) {
13662
13663 bool ConstexprVar = true;
13664
13665 // We know if we are here that we are in a context that we might require
13666 // a constant expression or a context that requires a constant
13667 // value. But if we are initializing a value we don't know if it is a
13668 // constexpr variable or not. We can check the EvaluatingDecl to determine
13669 // if it constexpr or not. If not then we don't want to emit a diagnostic.
13670 if (const auto *VD = dyn_cast_or_null<VarDecl>(
13671 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13672 ConstexprVar = VD->isConstexpr();
13673
13674 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13675 const EnumDecl *ED = ET->getDecl();
13676 // Check that the value is within the range of the enumeration values.
13677 //
13678 // This corressponds to [expr.static.cast]p10 which says:
13679 // A value of integral or enumeration type can be explicitly converted
13680 // to a complete enumeration type ... If the enumeration type does not
13681 // have a fixed underlying type, the value is unchanged if the original
13682 // value is within the range of the enumeration values ([dcl.enum]), and
13683 // otherwise, the behavior is undefined.
13684 //
13685 // This was resolved as part of DR2338 which has CD5 status.
13686 if (!ED->isFixed()) {
13687 llvm::APInt Min;
13688 llvm::APInt Max;
13689
13690 ED->getValueRange(Max, Min);
13691 --Max;
13692
13693 if (ED->getNumNegativeBits() && ConstexprVar &&
13694 (Max.slt(Result.getInt().getSExtValue()) ||
13695 Min.sgt(Result.getInt().getSExtValue())))
13696 Info.Ctx.getDiagnostics().Report(
13697 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13698 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13699 << Max.getSExtValue();
13700 else if (!ED->getNumNegativeBits() && ConstexprVar &&
13701 Max.ult(Result.getInt().getZExtValue()))
13702 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13703 diag::warn_constexpr_unscoped_enum_out_of_range)
13704 << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
13705 }
13706 }
13707
13708 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13709 Result.getInt()), E);
13710 }
13711
13712 case CK_PointerToIntegral: {
13713 CCEDiag(E, diag::note_constexpr_invalid_cast)
13714 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13715
13716 LValue LV;
13717 if (!EvaluatePointer(SubExpr, LV, Info))
13718 return false;
13719
13720 if (LV.getLValueBase()) {
13721 // Only allow based lvalue casts if they are lossless.
13722 // FIXME: Allow a larger integer size than the pointer size, and allow
13723 // narrowing back down to pointer width in subsequent integral casts.
13724 // FIXME: Check integer type's active bits, not its type size.
13725 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13726 return Error(E);
13727
13728 LV.Designator.setInvalid();
13729 LV.moveInto(Result);
13730 return true;
13731 }
13732
13733 APSInt AsInt;
13734 APValue V;
13735 LV.moveInto(V);
13736 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13737 llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "clang/lib/AST/ExprConstant.cpp"
, 13737)
;
13738
13739 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13740 }
13741
13742 case CK_IntegralComplexToReal: {
13743 ComplexValue C;
13744 if (!EvaluateComplex(SubExpr, C, Info))
13745 return false;
13746 return Success(C.getComplexIntReal(), E);
13747 }
13748
13749 case CK_FloatingToIntegral: {
13750 APFloat F(0.0);
13751 if (!EvaluateFloat(SubExpr, F, Info))
13752 return false;
13753
13754 APSInt Value;
13755 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13756 return false;
13757 return Success(Value, E);
13758 }
13759 }
13760
13761 llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value"
, "clang/lib/AST/ExprConstant.cpp", 13761)
;
13762}
13763
13764bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13765 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13766 ComplexValue LV;
13767 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13768 return false;
13769 if (!LV.isComplexInt())
13770 return Error(E);
13771 return Success(LV.getComplexIntReal(), E);
13772 }
13773
13774 return Visit(E->getSubExpr());
13775}
13776
13777bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13778 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13779 ComplexValue LV;
13780 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13781 return false;
13782 if (!LV.isComplexInt())
13783 return Error(E);
13784 return Success(LV.getComplexIntImag(), E);
13785 }
13786
13787 VisitIgnoredValue(E->getSubExpr());
13788 return Success(0, E);
13789}
13790
13791bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13792 return Success(E->getPackLength(), E);
13793}
13794
13795bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13796 return Success(E->getValue(), E);
13797}
13798
13799bool IntExprEvaluator::VisitConceptSpecializationExpr(
13800 const ConceptSpecializationExpr *E) {
13801 return Success(E->isSatisfied(), E);
13802}
13803
13804bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13805 return Success(E->isSatisfied(), E);
13806}
13807
13808bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13809 switch (E->getOpcode()) {
13810 default:
13811 // Invalid unary operators
13812 return Error(E);
13813 case UO_Plus:
13814 // The result is just the value.
13815 return Visit(E->getSubExpr());
13816 case UO_Minus: {
13817 if (!Visit(E->getSubExpr())) return false;
13818 if (!Result.isFixedPoint())
13819 return Error(E);
13820 bool Overflowed;
13821 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13822 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13823 return false;
13824 return Success(Negated, E);
13825 }
13826 case UO_LNot: {
13827 bool bres;
13828 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13829 return false;
13830 return Success(!bres, E);
13831 }
13832 }
13833}
13834
13835bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13836 const Expr *SubExpr = E->getSubExpr();
13837 QualType DestType = E->getType();
13838 assert(DestType->isFixedPointType() &&(static_cast <bool> (DestType->isFixedPointType() &&
"Expected destination type to be a fixed point type") ? void
(0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\""
, "clang/lib/AST/ExprConstant.cpp", 13839, __extension__ __PRETTY_FUNCTION__
))
13839 "Expected destination type to be a fixed point type")(static_cast <bool> (DestType->isFixedPointType() &&
"Expected destination type to be a fixed point type") ? void
(0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\""
, "clang/lib/AST/ExprConstant.cpp", 13839, __extension__ __PRETTY_FUNCTION__
))
;
13840 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13841
13842 switch (E->getCastKind()) {
13843 case CK_FixedPointCast: {
13844 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13845 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13846 return false;
13847 bool Overflowed;
13848 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13849 if (Overflowed) {
13850 if (Info.checkingForUndefinedBehavior())
13851 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13852 diag::warn_fixedpoint_constant_overflow)
13853 << Result.toString() << E->getType();
13854 if (!HandleOverflow(Info, E, Result, E->getType()))
13855 return false;
13856 }
13857 return Success(Result, E);
13858 }
13859 case CK_IntegralToFixedPoint: {
13860 APSInt Src;
13861 if (!EvaluateInteger(SubExpr, Src, Info))
13862 return false;
13863
13864 bool Overflowed;
13865 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13866 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13867
13868 if (Overflowed) {
13869 if (Info.checkingForUndefinedBehavior())
13870 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13871 diag::warn_fixedpoint_constant_overflow)
13872 << IntResult.toString() << E->getType();
13873 if (!HandleOverflow(Info, E, IntResult, E->getType()))
13874 return false;
13875 }
13876
13877 return Success(IntResult, E);
13878 }
13879 case CK_FloatingToFixedPoint: {
13880 APFloat Src(0.0);
13881 if (!EvaluateFloat(SubExpr, Src, Info))
13882 return false;
13883
13884 bool Overflowed;
13885 APFixedPoint Result = APFixedPoint::getFromFloatValue(
13886 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13887
13888 if (Overflowed) {
13889 if (Info.checkingForUndefinedBehavior())
13890 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13891 diag::warn_fixedpoint_constant_overflow)
13892 << Result.toString() << E->getType();
13893 if (!HandleOverflow(Info, E, Result, E->getType()))
13894 return false;
13895 }
13896
13897 return Success(Result, E);
13898 }
13899 case CK_NoOp:
13900 case CK_LValueToRValue:
13901 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13902 default:
13903 return Error(E);
13904 }
13905}
13906
13907bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13908 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13909 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13910
13911 const Expr *LHS = E->getLHS();
13912 const Expr *RHS = E->getRHS();
13913 FixedPointSemantics ResultFXSema =
13914 Info.Ctx.getFixedPointSemantics(E->getType());
13915
13916 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13917 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13918 return false;
13919 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13920 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13921 return false;
13922
13923 bool OpOverflow = false, ConversionOverflow = false;
13924 APFixedPoint Result(LHSFX.getSemantics());
13925 switch (E->getOpcode()) {
13926 case BO_Add: {
13927 Result = LHSFX.add(RHSFX, &OpOverflow)
13928 .convert(ResultFXSema, &ConversionOverflow);
13929 break;
13930 }
13931 case BO_Sub: {
13932 Result = LHSFX.sub(RHSFX, &OpOverflow)
13933 .convert(ResultFXSema, &ConversionOverflow);
13934 break;
13935 }
13936 case BO_Mul: {
13937 Result = LHSFX.mul(RHSFX, &OpOverflow)
13938 .convert(ResultFXSema, &ConversionOverflow);
13939 break;
13940 }
13941 case BO_Div: {
13942 if (RHSFX.getValue() == 0) {
13943 Info.FFDiag(E, diag::note_expr_divide_by_zero);
13944 return false;
13945 }
13946 Result = LHSFX.div(RHSFX, &OpOverflow)
13947 .convert(ResultFXSema, &ConversionOverflow);
13948 break;
13949 }
13950 case BO_Shl:
13951 case BO_Shr: {
13952 FixedPointSemantics LHSSema = LHSFX.getSemantics();
13953 llvm::APSInt RHSVal = RHSFX.getValue();
13954
13955 unsigned ShiftBW =
13956 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13957 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13958 // Embedded-C 4.1.6.2.2:
13959 // The right operand must be nonnegative and less than the total number
13960 // of (nonpadding) bits of the fixed-point operand ...
13961 if (RHSVal.isNegative())
13962 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13963 else if (Amt != RHSVal)
13964 Info.CCEDiag(E, diag::note_constexpr_large_shift)
13965 << RHSVal << E->getType() << ShiftBW;
13966
13967 if (E->getOpcode() == BO_Shl)
13968 Result = LHSFX.shl(Amt, &OpOverflow);
13969 else
13970 Result = LHSFX.shr(Amt, &OpOverflow);
13971 break;
13972 }
13973 default:
13974 return false;
13975 }
13976 if (OpOverflow || ConversionOverflow) {
13977 if (Info.checkingForUndefinedBehavior())
13978 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13979 diag::warn_fixedpoint_constant_overflow)
13980 << Result.toString() << E->getType();
13981 if (!HandleOverflow(Info, E, Result, E->getType()))
13982 return false;
13983 }
13984 return Success(Result, E);
13985}
13986
13987//===----------------------------------------------------------------------===//
13988// Float Evaluation
13989//===----------------------------------------------------------------------===//
13990
13991namespace {
13992class FloatExprEvaluator
13993 : public ExprEvaluatorBase<FloatExprEvaluator> {
13994 APFloat &Result;
13995public:
13996 FloatExprEvaluator(EvalInfo &info, APFloat &result)
13997 : ExprEvaluatorBaseTy(info), Result(result) {}
13998
13999 bool Success(const APValue &V, const Expr *e) {
14000 Result = V.getFloat();
14001 return true;
14002 }
14003
14004 bool ZeroInitialization(const Expr *E) {
14005 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14006 return true;
14007 }
14008
14009 bool VisitCallExpr(const CallExpr *E);
14010
14011 bool VisitUnaryOperator(const UnaryOperator *E);
14012 bool VisitBinaryOperator(const BinaryOperator *E);
14013 bool VisitFloatingLiteral(const FloatingLiteral *E);
14014 bool VisitCastExpr(const CastExpr *E);
14015
14016 bool VisitUnaryReal(const UnaryOperator *E);
14017 bool VisitUnaryImag(const UnaryOperator *E);
14018
14019 // FIXME: Missing: array subscript of vector, member of vector
14020};
14021} // end anonymous namespace
14022
14023static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14024 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14024, __extension__ __PRETTY_FUNCTION__))
;
14025 assert(E->isPRValue() && E->getType()->isRealFloatingType())(static_cast <bool> (E->isPRValue() && E->
getType()->isRealFloatingType()) ? void (0) : __assert_fail
("E->isPRValue() && E->getType()->isRealFloatingType()"
, "clang/lib/AST/ExprConstant.cpp", 14025, __extension__ __PRETTY_FUNCTION__
))
;
14026 return FloatExprEvaluator(Info, Result).Visit(E);
14027}
14028
14029static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14030 QualType ResultTy,
14031 const Expr *Arg,
14032 bool SNaN,
14033 llvm::APFloat &Result) {
14034 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14035 if (!S) return false;
14036
14037 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14038
14039 llvm::APInt fill;
14040
14041 // Treat empty strings as if they were zero.
14042 if (S->getString().empty())
14043 fill = llvm::APInt(32, 0);
14044 else if (S->getString().getAsInteger(0, fill))
14045 return false;
14046
14047 if (Context.getTargetInfo().isNan2008()) {
14048 if (SNaN)
14049 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14050 else
14051 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14052 } else {
14053 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14054 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14055 // a different encoding to what became a standard in 2008, and for pre-
14056 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14057 // sNaN. This is now known as "legacy NaN" encoding.
14058 if (SNaN)
14059 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14060 else
14061 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14062 }
14063
14064 return true;
14065}
14066
14067bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14068 if (!IsConstantEvaluatedBuiltinCall(E))
14069 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14070
14071 switch (E->getBuiltinCallee()) {
14072 default:
14073 return false;
14074
14075 case Builtin::BI__builtin_huge_val:
14076 case Builtin::BI__builtin_huge_valf:
14077 case Builtin::BI__builtin_huge_vall:
14078 case Builtin::BI__builtin_huge_valf16:
14079 case Builtin::BI__builtin_huge_valf128:
14080 case Builtin::BI__builtin_inf:
14081 case Builtin::BI__builtin_inff:
14082 case Builtin::BI__builtin_infl:
14083 case Builtin::BI__builtin_inff16:
14084 case Builtin::BI__builtin_inff128: {
14085 const llvm::fltSemantics &Sem =
14086 Info.Ctx.getFloatTypeSemantics(E->getType());
14087 Result = llvm::APFloat::getInf(Sem);
14088 return true;
14089 }
14090
14091 case Builtin::BI__builtin_nans:
14092 case Builtin::BI__builtin_nansf:
14093 case Builtin::BI__builtin_nansl:
14094 case Builtin::BI__builtin_nansf16:
14095 case Builtin::BI__builtin_nansf128:
14096 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14097 true, Result))
14098 return Error(E);
14099 return true;
14100
14101 case Builtin::BI__builtin_nan:
14102 case Builtin::BI__builtin_nanf:
14103 case Builtin::BI__builtin_nanl:
14104 case Builtin::BI__builtin_nanf16:
14105 case Builtin::BI__builtin_nanf128:
14106 // If this is __builtin_nan() turn this into a nan, otherwise we
14107 // can't constant fold it.
14108 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14109 false, Result))
14110 return Error(E);
14111 return true;
14112
14113 case Builtin::BI__builtin_fabs:
14114 case Builtin::BI__builtin_fabsf:
14115 case Builtin::BI__builtin_fabsl:
14116 case Builtin::BI__builtin_fabsf128:
14117 // The C standard says "fabs raises no floating-point exceptions,
14118 // even if x is a signaling NaN. The returned value is independent of
14119 // the current rounding direction mode." Therefore constant folding can
14120 // proceed without regard to the floating point settings.
14121 // Reference, WG14 N2478 F.10.4.3
14122 if (!EvaluateFloat(E->getArg(0), Result, Info))
14123 return false;
14124
14125 if (Result.isNegative())
14126 Result.changeSign();
14127 return true;
14128
14129 case Builtin::BI__arithmetic_fence:
14130 return EvaluateFloat(E->getArg(0), Result, Info);
14131
14132 // FIXME: Builtin::BI__builtin_powi
14133 // FIXME: Builtin::BI__builtin_powif
14134 // FIXME: Builtin::BI__builtin_powil
14135
14136 case Builtin::BI__builtin_copysign:
14137 case Builtin::BI__builtin_copysignf:
14138 case Builtin::BI__builtin_copysignl:
14139 case Builtin::BI__builtin_copysignf128: {
14140 APFloat RHS(0.);
14141 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14142 !EvaluateFloat(E->getArg(1), RHS, Info))
14143 return false;
14144 Result.copySign(RHS);
14145 return true;
14146 }
14147
14148 case Builtin::BI__builtin_fmax:
14149 case Builtin::BI__builtin_fmaxf:
14150 case Builtin::BI__builtin_fmaxl:
14151 case Builtin::BI__builtin_fmaxf16:
14152 case Builtin::BI__builtin_fmaxf128: {
14153 // TODO: Handle sNaN.
14154 APFloat RHS(0.);
14155 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14156 !EvaluateFloat(E->getArg(1), RHS, Info))
14157 return false;
14158 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14159 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14160 Result = RHS;
14161 else if (Result.isNaN() || RHS > Result)
14162 Result = RHS;
14163 return true;
14164 }
14165
14166 case Builtin::BI__builtin_fmin:
14167 case Builtin::BI__builtin_fminf:
14168 case Builtin::BI__builtin_fminl:
14169 case Builtin::BI__builtin_fminf16:
14170 case Builtin::BI__builtin_fminf128: {
14171 // TODO: Handle sNaN.
14172 APFloat RHS(0.);
14173 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14174 !EvaluateFloat(E->getArg(1), RHS, Info))
14175 return false;
14176 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14177 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14178 Result = RHS;
14179 else if (Result.isNaN() || RHS < Result)
14180 Result = RHS;
14181 return true;
14182 }
14183 }
14184}
14185
14186bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14187 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14188 ComplexValue CV;
14189 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14190 return false;
14191 Result = CV.FloatReal;
14192 return true;
14193 }
14194
14195 return Visit(E->getSubExpr());
14196}
14197
14198bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14199 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14200 ComplexValue CV;
14201 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14202 return false;
14203 Result = CV.FloatImag;
14204 return true;
14205 }
14206
14207 VisitIgnoredValue(E->getSubExpr());
14208 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14209 Result = llvm::APFloat::getZero(Sem);
14210 return true;
14211}
14212
14213bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14214 switch (E->getOpcode()) {
14215 default: return Error(E);
14216 case UO_Plus:
14217 return EvaluateFloat(E->getSubExpr(), Result, Info);
14218 case UO_Minus:
14219 // In C standard, WG14 N2478 F.3 p4
14220 // "the unary - raises no floating point exceptions,
14221 // even if the operand is signalling."
14222 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14223 return false;
14224 Result.changeSign();
14225 return true;
14226 }
14227}
14228
14229bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14230 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14231 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14232
14233 APFloat RHS(0.0);
14234 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14235 if (!LHSOK && !Info.noteFailure())
14236 return false;
14237 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14238 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14239}
14240
14241bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14242 Result = E->getValue();
14243 return true;
14244}
14245
14246bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14247 const Expr* SubExpr = E->getSubExpr();
14248
14249 switch (E->getCastKind()) {
14250 default:
14251 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14252
14253 case CK_IntegralToFloating: {
14254 APSInt IntResult;
14255 const FPOptions FPO = E->getFPFeaturesInEffect(
14256 Info.Ctx.getLangOpts());
14257 return EvaluateInteger(SubExpr, IntResult, Info) &&
14258 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14259 IntResult, E->getType(), Result);
14260 }
14261
14262 case CK_FixedPointToFloating: {
14263 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14264 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14265 return false;
14266 Result =
14267 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14268 return true;
14269 }
14270
14271 case CK_FloatingCast: {
14272 if (!Visit(SubExpr))
14273 return false;
14274 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14275 Result);
14276 }
14277
14278 case CK_FloatingComplexToReal: {
14279 ComplexValue V;
14280 if (!EvaluateComplex(SubExpr, V, Info))
14281 return false;
14282 Result = V.getComplexFloatReal();
14283 return true;
14284 }
14285 }
14286}
14287
14288//===----------------------------------------------------------------------===//
14289// Complex Evaluation (for float and integer)
14290//===----------------------------------------------------------------------===//
14291
14292namespace {
14293class ComplexExprEvaluator
14294 : public ExprEvaluatorBase<ComplexExprEvaluator> {
14295 ComplexValue &Result;
14296
14297public:
14298 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14299 : ExprEvaluatorBaseTy(info), Result(Result) {}
14300
14301 bool Success(const APValue &V, const Expr *e) {
14302 Result.setFrom(V);
14303 return true;
14304 }
14305
14306 bool ZeroInitialization(const Expr *E);
14307
14308 //===--------------------------------------------------------------------===//
14309 // Visitor Methods
14310 //===--------------------------------------------------------------------===//
14311
14312 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14313 bool VisitCastExpr(const CastExpr *E);
14314 bool VisitBinaryOperator(const BinaryOperator *E);
14315 bool VisitUnaryOperator(const UnaryOperator *E);
14316 bool VisitInitListExpr(const InitListExpr *E);
14317 bool VisitCallExpr(const CallExpr *E);
14318};
14319} // end anonymous namespace
14320
14321static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14322 EvalInfo &Info) {
14323 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14323, __extension__ __PRETTY_FUNCTION__))
;
14324 assert(E->isPRValue() && E->getType()->isAnyComplexType())(static_cast <bool> (E->isPRValue() && E->
getType()->isAnyComplexType()) ? void (0) : __assert_fail (
"E->isPRValue() && E->getType()->isAnyComplexType()"
, "clang/lib/AST/ExprConstant.cpp", 14324, __extension__ __PRETTY_FUNCTION__
))
;
14325 return ComplexExprEvaluator(Info, Result).Visit(E);
14326}
14327
14328bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14329 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14330 if (ElemTy->isRealFloatingType()) {
14331 Result.makeComplexFloat();
14332 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14333 Result.FloatReal = Zero;
14334 Result.FloatImag = Zero;
14335 } else {
14336 Result.makeComplexInt();
14337 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14338 Result.IntReal = Zero;
14339 Result.IntImag = Zero;
14340 }
14341 return true;
14342}
14343
14344bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14345 const Expr* SubExpr = E->getSubExpr();
14346
14347 if (SubExpr->getType()->isRealFloatingType()) {
14348 Result.makeComplexFloat();
14349 APFloat &Imag = Result.FloatImag;
14350 if (!EvaluateFloat(SubExpr, Imag, Info))
14351 return false;
14352
14353 Result.FloatReal = APFloat(Imag.getSemantics());
14354 return true;
14355 } else {
14356 assert(SubExpr->getType()->isIntegerType() &&(static_cast <bool> (SubExpr->getType()->isIntegerType
() && "Unexpected imaginary literal.") ? void (0) : __assert_fail
("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\""
, "clang/lib/AST/ExprConstant.cpp", 14357, __extension__ __PRETTY_FUNCTION__
))
14357 "Unexpected imaginary literal.")(static_cast <bool> (SubExpr->getType()->isIntegerType
() && "Unexpected imaginary literal.") ? void (0) : __assert_fail
("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\""
, "clang/lib/AST/ExprConstant.cpp", 14357, __extension__ __PRETTY_FUNCTION__
))
;
14358
14359 Result.makeComplexInt();
14360 APSInt &Imag = Result.IntImag;
14361 if (!EvaluateInteger(SubExpr, Imag, Info))
14362 return false;
14363
14364 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14365 return true;
14366 }
14367}
14368
14369bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14370
14371 switch (E->getCastKind()) {
14372 case CK_BitCast:
14373 case CK_BaseToDerived:
14374 case CK_DerivedToBase:
14375 case CK_UncheckedDerivedToBase:
14376 case CK_Dynamic:
14377 case CK_ToUnion:
14378 case CK_ArrayToPointerDecay:
14379 case CK_FunctionToPointerDecay:
14380 case CK_NullToPointer:
14381 case CK_NullToMemberPointer:
14382 case CK_BaseToDerivedMemberPointer:
14383 case CK_DerivedToBaseMemberPointer:
14384 case CK_MemberPointerToBoolean:
14385 case CK_ReinterpretMemberPointer:
14386 case CK_ConstructorConversion:
14387 case CK_IntegralToPointer:
14388 case CK_PointerToIntegral:
14389 case CK_PointerToBoolean:
14390 case CK_ToVoid:
14391 case CK_VectorSplat:
14392 case CK_IntegralCast:
14393 case CK_BooleanToSignedIntegral:
14394 case CK_IntegralToBoolean:
14395 case CK_IntegralToFloating:
14396 case CK_FloatingToIntegral:
14397 case CK_FloatingToBoolean:
14398 case CK_FloatingCast:
14399 case CK_CPointerToObjCPointerCast:
14400 case CK_BlockPointerToObjCPointerCast:
14401 case CK_AnyPointerToBlockPointerCast:
14402 case CK_ObjCObjectLValueCast:
14403 case CK_FloatingComplexToReal:
14404 case CK_FloatingComplexToBoolean:
14405 case CK_IntegralComplexToReal:
14406 case CK_IntegralComplexToBoolean:
14407 case CK_ARCProduceObject:
14408 case CK_ARCConsumeObject:
14409 case CK_ARCReclaimReturnedObject:
14410 case CK_ARCExtendBlockObject:
14411 case CK_CopyAndAutoreleaseBlockObject:
14412 case CK_BuiltinFnToFnPtr:
14413 case CK_ZeroToOCLOpaqueType:
14414 case CK_NonAtomicToAtomic:
14415 case CK_AddressSpaceConversion:
14416 case CK_IntToOCLSampler:
14417 case CK_FloatingToFixedPoint:
14418 case CK_FixedPointToFloating:
14419 case CK_FixedPointCast:
14420 case CK_FixedPointToBoolean:
14421 case CK_FixedPointToIntegral:
14422 case CK_IntegralToFixedPoint:
14423 case CK_MatrixCast:
14424 llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value"
, "clang/lib/AST/ExprConstant.cpp", 14424)
;
14425
14426 case CK_LValueToRValue:
14427 case CK_AtomicToNonAtomic:
14428 case CK_NoOp:
14429 case CK_LValueToRValueBitCast:
14430 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14431
14432 case CK_Dependent:
14433 case CK_LValueBitCast:
14434 case CK_UserDefinedConversion:
14435 return Error(E);
14436
14437 case CK_FloatingRealToComplex: {
14438 APFloat &Real = Result.FloatReal;
14439 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14440 return false;
14441
14442 Result.makeComplexFloat();
14443 Result.FloatImag = APFloat(Real.getSemantics());
14444 return true;
14445 }
14446
14447 case CK_FloatingComplexCast: {
14448 if (!Visit(E->getSubExpr()))
14449 return false;
14450
14451 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14452 QualType From
14453 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14454
14455 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14456 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14457 }
14458
14459 case CK_FloatingComplexToIntegralComplex: {
14460 if (!Visit(E->getSubExpr()))
14461 return false;
14462
14463 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14464 QualType From
14465 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14466 Result.makeComplexInt();
14467 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14468 To, Result.IntReal) &&
14469 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14470 To, Result.IntImag);
14471 }
14472
14473 case CK_IntegralRealToComplex: {
14474 APSInt &Real = Result.IntReal;
14475 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14476 return false;
14477
14478 Result.makeComplexInt();
14479 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14480 return true;
14481 }
14482
14483 case CK_IntegralComplexCast: {
14484 if (!Visit(E->getSubExpr()))
14485 return false;
14486
14487 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14488 QualType From
14489 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14490
14491 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14492 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14493 return true;
14494 }
14495
14496 case CK_IntegralComplexToFloatingComplex: {
14497 if (!Visit(E->getSubExpr()))
14498 return false;
14499
14500 const FPOptions FPO = E->getFPFeaturesInEffect(
14501 Info.Ctx.getLangOpts());
14502 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14503 QualType From
14504 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14505 Result.makeComplexFloat();
14506 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14507 To, Result.FloatReal) &&
14508 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14509 To, Result.FloatImag);
14510 }
14511 }
14512
14513 llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value"
, "clang/lib/AST/ExprConstant.cpp", 14513)
;
14514}
14515
14516bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14517 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14518 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14519
14520 // Track whether the LHS or RHS is real at the type system level. When this is
14521 // the case we can simplify our evaluation strategy.
14522 bool LHSReal = false, RHSReal = false;
14523
14524 bool LHSOK;
14525 if (E->getLHS()->getType()->isRealFloatingType()) {
14526 LHSReal = true;
14527 APFloat &Real = Result.FloatReal;
14528 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14529 if (LHSOK) {
14530 Result.makeComplexFloat();
14531 Result.FloatImag = APFloat(Real.getSemantics());
14532 }
14533 } else {
14534 LHSOK = Visit(E->getLHS());
14535 }
14536 if (!LHSOK && !Info.noteFailure())
14537 return false;
14538
14539 ComplexValue RHS;
14540 if (E->getRHS()->getType()->isRealFloatingType()) {
14541 RHSReal = true;
14542 APFloat &Real = RHS.FloatReal;
14543 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14544 return false;
14545 RHS.makeComplexFloat();
14546 RHS.FloatImag = APFloat(Real.getSemantics());
14547 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14548 return false;
14549
14550 assert(!(LHSReal && RHSReal) &&(static_cast <bool> (!(LHSReal && RHSReal) &&
"Cannot have both operands of a complex operation be real.")
? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\""
, "clang/lib/AST/ExprConstant.cpp", 14551, __extension__ __PRETTY_FUNCTION__
))
14551 "Cannot have both operands of a complex operation be real.")(static_cast <bool> (!(LHSReal && RHSReal) &&
"Cannot have both operands of a complex operation be real.")
? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\""
, "clang/lib/AST/ExprConstant.cpp", 14551, __extension__ __PRETTY_FUNCTION__
))
;
14552 switch (E->getOpcode()) {
14553 default: return Error(E);
14554 case BO_Add:
14555 if (Result.isComplexFloat()) {
14556 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14557 APFloat::rmNearestTiesToEven);
14558 if (LHSReal)
14559 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14560 else if (!RHSReal)
14561 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14562 APFloat::rmNearestTiesToEven);
14563 } else {
14564 Result.getComplexIntReal() += RHS.getComplexIntReal();
14565 Result.getComplexIntImag() += RHS.getComplexIntImag();
14566 }
14567 break;
14568 case BO_Sub:
14569 if (Result.isComplexFloat()) {
14570 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14571 APFloat::rmNearestTiesToEven);
14572 if (LHSReal) {
14573 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14574 Result.getComplexFloatImag().changeSign();
14575 } else if (!RHSReal) {
14576 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14577 APFloat::rmNearestTiesToEven);
14578 }
14579 } else {
14580 Result.getComplexIntReal() -= RHS.getComplexIntReal();
14581 Result.getComplexIntImag() -= RHS.getComplexIntImag();
14582 }
14583 break;
14584 case BO_Mul:
14585 if (Result.isComplexFloat()) {
14586 // This is an implementation of complex multiplication according to the
14587 // constraints laid out in C11 Annex G. The implementation uses the
14588 // following naming scheme:
14589 // (a + ib) * (c + id)
14590 ComplexValue LHS = Result;
14591 APFloat &A = LHS.getComplexFloatReal();
14592 APFloat &B = LHS.getComplexFloatImag();
14593 APFloat &C = RHS.getComplexFloatReal();
14594 APFloat &D = RHS.getComplexFloatImag();
14595 APFloat &ResR = Result.getComplexFloatReal();
14596 APFloat &ResI = Result.getComplexFloatImag();
14597 if (LHSReal) {
14598 assert(!RHSReal && "Cannot have two real operands for a complex op!")(static_cast <bool> (!RHSReal && "Cannot have two real operands for a complex op!"
) ? void (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\""
, "clang/lib/AST/ExprConstant.cpp", 14598, __extension__ __PRETTY_FUNCTION__
))
;
14599 ResR = A * C;
14600 ResI = A * D;
14601 } else if (RHSReal) {
14602 ResR = C * A;
14603 ResI = C * B;
14604 } else {
14605 // In the fully general case, we need to handle NaNs and infinities
14606 // robustly.
14607 APFloat AC = A * C;
14608 APFloat BD = B * D;
14609 APFloat AD = A * D;
14610 APFloat BC = B * C;
14611 ResR = AC - BD;
14612 ResI = AD + BC;
14613 if (ResR.isNaN() && ResI.isNaN()) {
14614 bool Recalc = false;
14615 if (A.isInfinity() || B.isInfinity()) {
14616 A = APFloat::copySign(
14617 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14618 B = APFloat::copySign(
14619 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14620 if (C.isNaN())
14621 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14622 if (D.isNaN())
14623 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14624 Recalc = true;
14625 }
14626 if (C.isInfinity() || D.isInfinity()) {
14627 C = APFloat::copySign(
14628 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14629 D = APFloat::copySign(
14630 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14631 if (A.isNaN())
14632 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14633 if (B.isNaN())
14634 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14635 Recalc = true;
14636 }
14637 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14638 AD.isInfinity() || BC.isInfinity())) {
14639 if (A.isNaN())
14640 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14641 if (B.isNaN())
14642 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14643 if (C.isNaN())
14644 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14645 if (D.isNaN())
14646 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14647 Recalc = true;
14648 }
14649 if (Recalc) {
14650 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14651 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14652 }
14653 }
14654 }
14655 } else {
14656 ComplexValue LHS = Result;
14657 Result.getComplexIntReal() =
14658 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14659 LHS.getComplexIntImag() * RHS.getComplexIntImag());
14660 Result.getComplexIntImag() =
14661 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14662 LHS.getComplexIntImag() * RHS.getComplexIntReal());
14663 }
14664 break;
14665 case BO_Div:
14666 if (Result.isComplexFloat()) {
14667 // This is an implementation of complex division according to the
14668 // constraints laid out in C11 Annex G. The implementation uses the
14669 // following naming scheme:
14670 // (a + ib) / (c + id)
14671 ComplexValue LHS = Result;
14672 APFloat &A = LHS.getComplexFloatReal();
14673 APFloat &B = LHS.getComplexFloatImag();
14674 APFloat &C = RHS.getComplexFloatReal();
14675 APFloat &D = RHS.getComplexFloatImag();
14676 APFloat &ResR = Result.getComplexFloatReal();
14677 APFloat &ResI = Result.getComplexFloatImag();
14678 if (RHSReal) {
14679 ResR = A / C;
14680 ResI = B / C;
14681 } else {
14682 if (LHSReal) {
14683 // No real optimizations we can do here, stub out with zero.
14684 B = APFloat::getZero(A.getSemantics());
14685 }
14686 int DenomLogB = 0;
14687 APFloat MaxCD = maxnum(abs(C), abs(D));
14688 if (MaxCD.isFinite()) {
14689 DenomLogB = ilogb(MaxCD);
14690 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14691 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14692 }
14693 APFloat Denom = C * C + D * D;
14694 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14695 APFloat::rmNearestTiesToEven);
14696 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14697 APFloat::rmNearestTiesToEven);
14698 if (ResR.isNaN() && ResI.isNaN()) {
14699 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14700 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14701 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14702 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14703 D.isFinite()) {
14704 A = APFloat::copySign(
14705 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14706 B = APFloat::copySign(
14707 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14708 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14709 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14710 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14711 C = APFloat::copySign(
14712 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14713 D = APFloat::copySign(
14714 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14715 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14716 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14717 }
14718 }
14719 }
14720 } else {
14721 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14722 return Error(E, diag::note_expr_divide_by_zero);
14723
14724 ComplexValue LHS = Result;
14725 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14726 RHS.getComplexIntImag() * RHS.getComplexIntImag();
14727 Result.getComplexIntReal() =
14728 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14729 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14730 Result.getComplexIntImag() =
14731 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14732 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14733 }
14734 break;
14735 }
14736
14737 return true;
14738}
14739
14740bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14741 // Get the operand value into 'Result'.
14742 if (!Visit(E->getSubExpr()))
14743 return false;
14744
14745 switch (E->getOpcode()) {
14746 default:
14747 return Error(E);
14748 case UO_Extension:
14749 return true;
14750 case UO_Plus:
14751 // The result is always just the subexpr.
14752 return true;
14753 case UO_Minus:
14754 if (Result.isComplexFloat()) {
14755 Result.getComplexFloatReal().changeSign();
14756 Result.getComplexFloatImag().changeSign();
14757 }
14758 else {
14759 Result.getComplexIntReal() = -Result.getComplexIntReal();
14760 Result.getComplexIntImag() = -Result.getComplexIntImag();
14761 }
14762 return true;
14763 case UO_Not:
14764 if (Result.isComplexFloat())
14765 Result.getComplexFloatImag().changeSign();
14766 else
14767 Result.getComplexIntImag() = -Result.getComplexIntImag();
14768 return true;
14769 }
14770}
14771
14772bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14773 if (E->getNumInits() == 2) {
14774 if (E->getType()->isComplexType()) {
14775 Result.makeComplexFloat();
14776 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14777 return false;
14778 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14779 return false;
14780 } else {
14781 Result.makeComplexInt();
14782 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14783 return false;
14784 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14785 return false;
14786 }
14787 return true;
14788 }
14789 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14790}
14791
14792bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14793 if (!IsConstantEvaluatedBuiltinCall(E))
14794 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14795
14796 switch (E->getBuiltinCallee()) {
14797 case Builtin::BI__builtin_complex:
14798 Result.makeComplexFloat();
14799 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14800 return false;
14801 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14802 return false;
14803 return true;
14804
14805 default:
14806 return false;
14807 }
14808}
14809
14810//===----------------------------------------------------------------------===//
14811// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14812// implicit conversion.
14813//===----------------------------------------------------------------------===//
14814
14815namespace {
14816class AtomicExprEvaluator :
14817 public ExprEvaluatorBase<AtomicExprEvaluator> {
14818 const LValue *This;
14819 APValue &Result;
14820public:
14821 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14822 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14823
14824 bool Success(const APValue &V, const Expr *E) {
14825 Result = V;
14826 return true;
14827 }
14828
14829 bool ZeroInitialization(const Expr *E) {
14830 ImplicitValueInitExpr VIE(
14831 E->getType()->castAs<AtomicType>()->getValueType());
14832 // For atomic-qualified class (and array) types in C++, initialize the
14833 // _Atomic-wrapped subobject directly, in-place.
14834 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14835 : Evaluate(Result, Info, &VIE);
14836 }
14837
14838 bool VisitCastExpr(const CastExpr *E) {
14839 switch (E->getCastKind()) {
14840 default:
14841 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14842 case CK_NullToPointer:
14843 case CK_NonAtomicToAtomic:
14844 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14845 : Evaluate(Result, Info, E->getSubExpr());
14846 }
14847 }
14848};
14849} // end anonymous namespace
14850
14851static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14852 EvalInfo &Info) {
14853 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14853, __extension__ __PRETTY_FUNCTION__))
;
14854 assert(E->isPRValue() && E->getType()->isAtomicType())(static_cast <bool> (E->isPRValue() && E->
getType()->isAtomicType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isAtomicType()"
, "clang/lib/AST/ExprConstant.cpp", 14854, __extension__ __PRETTY_FUNCTION__
))
;
14855 return AtomicExprEvaluator(Info, This, Result).Visit(E);
14856}
14857
14858//===----------------------------------------------------------------------===//
14859// Void expression evaluation, primarily for a cast to void on the LHS of a
14860// comma operator
14861//===----------------------------------------------------------------------===//
14862
14863namespace {
14864class VoidExprEvaluator
14865 : public ExprEvaluatorBase<VoidExprEvaluator> {
14866public:
14867 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14868
14869 bool Success(const APValue &V, const Expr *e) { return true; }
14870
14871 bool ZeroInitialization(const Expr *E) { return true; }
14872
14873 bool VisitCastExpr(const CastExpr *E) {
14874 switch (E->getCastKind()) {
14875 default:
14876 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14877 case CK_ToVoid:
14878 VisitIgnoredValue(E->getSubExpr());
14879 return true;
14880 }
14881 }
14882
14883 bool VisitCallExpr(const CallExpr *E) {
14884 if (!IsConstantEvaluatedBuiltinCall(E))
14885 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14886
14887 switch (E->getBuiltinCallee()) {
14888 case Builtin::BI__assume:
14889 case Builtin::BI__builtin_assume:
14890 // The argument is not evaluated!
14891 return true;
14892
14893 case Builtin::BI__builtin_operator_delete:
14894 return HandleOperatorDeleteCall(Info, E);
14895
14896 default:
14897 return false;
14898 }
14899 }
14900
14901 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14902};
14903} // end anonymous namespace
14904
14905bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14906 // We cannot speculatively evaluate a delete expression.
14907 if (Info.SpeculativeEvaluationDepth)
14908 return false;
14909
14910 FunctionDecl *OperatorDelete = E->getOperatorDelete();
14911 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14912 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14913 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14914 return false;
14915 }
14916
14917 const Expr *Arg = E->getArgument();
14918
14919 LValue Pointer;
14920 if (!EvaluatePointer(Arg, Pointer, Info))
14921 return false;
14922 if (Pointer.Designator.Invalid)
14923 return false;
14924
14925 // Deleting a null pointer has no effect.
14926 if (Pointer.isNullPointer()) {
14927 // This is the only case where we need to produce an extension warning:
14928 // the only other way we can succeed is if we find a dynamic allocation,
14929 // and we will have warned when we allocated it in that case.
14930 if (!Info.getLangOpts().CPlusPlus20)
14931 Info.CCEDiag(E, diag::note_constexpr_new);
14932 return true;
14933 }
14934
14935 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
14936 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14937 if (!Alloc)
14938 return false;
14939 QualType AllocType = Pointer.Base.getDynamicAllocType();
14940
14941 // For the non-array case, the designator must be empty if the static type
14942 // does not have a virtual destructor.
14943 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14944 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14945 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14946 << Arg->getType()->getPointeeType() << AllocType;
14947 return false;
14948 }
14949
14950 // For a class type with a virtual destructor, the selected operator delete
14951 // is the one looked up when building the destructor.
14952 if (!E->isArrayForm() && !E->isGlobalDelete()) {
14953 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14954 if (VirtualDelete &&
14955 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14956 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14957 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14958 return false;
14959 }
14960 }
14961
14962 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14963 (*Alloc)->Value, AllocType))
14964 return false;
14965
14966 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14967 // The element was already erased. This means the destructor call also
14968 // deleted the object.
14969 // FIXME: This probably results in undefined behavior before we get this
14970 // far, and should be diagnosed elsewhere first.
14971 Info.FFDiag(E, diag::note_constexpr_double_delete);
14972 return false;
14973 }
14974
14975 return true;
14976}
14977
14978static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14979 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14979, __extension__ __PRETTY_FUNCTION__))
;
14980 assert(E->isPRValue() && E->getType()->isVoidType())(static_cast <bool> (E->isPRValue() && E->
getType()->isVoidType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVoidType()"
, "clang/lib/AST/ExprConstant.cpp", 14980, __extension__ __PRETTY_FUNCTION__
))
;
14981 return VoidExprEvaluator(Info).Visit(E);
14982}
14983
14984//===----------------------------------------------------------------------===//
14985// Top level Expr::EvaluateAsRValue method.
14986//===----------------------------------------------------------------------===//
14987
14988static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14989 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14989, __extension__ __PRETTY_FUNCTION__))
;
14990 // In C, function designators are not lvalues, but we evaluate them as if they
14991 // are.
14992 QualType T = E->getType();
14993 if (E->isGLValue() || T->isFunctionType()) {
14994 LValue LV;
14995 if (!EvaluateLValue(E, LV, Info))
14996 return false;
14997 LV.moveInto(Result);
14998 } else if (T->isVectorType()) {
14999 if (!EvaluateVector(E, Result, Info))
15000 return false;
15001 } else if (T->isIntegralOrEnumerationType()) {
15002 if (!IntExprEvaluator(Info, Result).Visit(E))
15003 return false;
15004 } else if (T->hasPointerRepresentation()) {
15005 LValue LV;
15006 if (!EvaluatePointer(E, LV, Info))
15007 return false;
15008 LV.moveInto(Result);
15009 } else if (T->isRealFloatingType()) {
15010 llvm::APFloat F(0.0);
15011 if (!EvaluateFloat(E, F, Info))
15012 return false;
15013 Result = APValue(F);
15014 } else if (T->isAnyComplexType()) {
15015 ComplexValue C;
15016 if (!EvaluateComplex(E, C, Info))
15017 return false;
15018 C.moveInto(Result);
15019 } else if (T->isFixedPointType()) {
15020 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15021 } else if (T->isMemberPointerType()) {
15022 MemberPtr P;
15023 if (!EvaluateMemberPointer(E, P, Info))
15024 return false;
15025 P.moveInto(Result);
15026 return true;
15027 } else if (T->isArrayType()) {
15028 LValue LV;
15029 APValue &Value =
15030 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15031 if (!EvaluateArray(E, LV, Value, Info))
15032 return false;
15033 Result = Value;
15034 } else if (T->isRecordType()) {
15035 LValue LV;
15036 APValue &Value =
15037 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15038 if (!EvaluateRecord(E, LV, Value, Info))
15039 return false;
15040 Result = Value;
15041 } else if (T->isVoidType()) {
15042 if (!Info.getLangOpts().CPlusPlus11)
15043 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15044 << E->getType();
15045 if (!EvaluateVoid(E, Info))
15046 return false;
15047 } else if (T->isAtomicType()) {
15048 QualType Unqual = T.getAtomicUnqualifiedType();
15049 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15050 LValue LV;
15051 APValue &Value = Info.CurrentCall->createTemporary(
15052 E, Unqual, ScopeKind::FullExpression, LV);
15053 if (!EvaluateAtomic(E, &LV, Value, Info))
15054 return false;
15055 } else {
15056 if (!EvaluateAtomic(E, nullptr, Result, Info))
15057 return false;
15058 }
15059 } else if (Info.getLangOpts().CPlusPlus11) {
15060 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15061 return false;
15062 } else {
15063 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15064 return false;
15065 }
15066
15067 return true;
15068}
15069
15070/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15071/// cases, the in-place evaluation is essential, since later initializers for
15072/// an object can indirectly refer to subobjects which were initialized earlier.
15073static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15074 const Expr *E, bool AllowNonLiteralTypes) {
15075 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15075, __extension__ __PRETTY_FUNCTION__))
;
15076
15077 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15078 return false;
15079
15080 if (E->isPRValue()) {
15081 // Evaluate arrays and record types in-place, so that later initializers can
15082 // refer to earlier-initialized members of the object.
15083 QualType T = E->getType();
15084 if (T->isArrayType())
15085 return EvaluateArray(E, This, Result, Info);
15086 else if (T->isRecordType())
15087 return EvaluateRecord(E, This, Result, Info);
15088 else if (T->isAtomicType()) {
15089 QualType Unqual = T.getAtomicUnqualifiedType();
15090 if (Unqual->isArrayType() || Unqual->isRecordType())
15091 return EvaluateAtomic(E, &This, Result, Info);
15092 }
15093 }
15094
15095 // For any other type, in-place evaluation is unimportant.
15096 return Evaluate(Result, Info, E);
15097}
15098
15099/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15100/// lvalue-to-rvalue cast if it is an lvalue.
15101static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15102 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15102, __extension__ __PRETTY_FUNCTION__))
;
15103
15104 if (E->getType().isNull())
15105 return false;
15106
15107 if (!CheckLiteralType(Info, E))
15108 return false;
15109
15110 if (Info.EnableNewConstInterp) {
15111 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15112 return false;
15113 } else {
15114 if (!::Evaluate(Result, Info, E))
15115 return false;
15116 }
15117
15118 // Implicit lvalue-to-rvalue cast.
15119 if (E->isGLValue()) {
15120 LValue LV;
15121 LV.setFrom(Info.Ctx, Result);
15122 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15123 return false;
15124 }
15125
15126 // Check this core constant expression is a constant expression.
15127 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15128 ConstantExprKind::Normal) &&
15129 CheckMemoryLeaks(Info);
15130}
15131
15132static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15133 const ASTContext &Ctx, bool &IsConst) {
15134 // Fast-path evaluations of integer literals, since we sometimes see files
15135 // containing vast quantities of these.
15136 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15137 Result.Val = APValue(APSInt(L->getValue(),
15138 L->getType()->isUnsignedIntegerType()));
15139 IsConst = true;
15140 return true;
15141 }
15142
15143 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15144 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15145 IsConst = true;
15146 return true;
15147 }
15148
15149 // This case should be rare, but we need to check it before we check on
15150 // the type below.
15151 if (Exp->getType().isNull()) {
15152 IsConst = false;
15153 return true;
15154 }
15155
15156 // FIXME: Evaluating values of large array and record types can cause
15157 // performance problems. Only do so in C++11 for now.
15158 if (Exp->isPRValue() &&
15159 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15160 !Ctx.getLangOpts().CPlusPlus11) {
15161 IsConst = false;
15162 return true;
15163 }
15164 return false;
15165}
15166
15167static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15168 Expr::SideEffectsKind SEK) {
15169 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15170 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15171}
15172
15173static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15174 const ASTContext &Ctx, EvalInfo &Info) {
15175 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15175, __extension__ __PRETTY_FUNCTION__))
;
15176 bool IsConst;
15177 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15178 return IsConst;
15179
15180 return EvaluateAsRValue(Info, E, Result.Val);
15181}
15182
15183static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15184 const ASTContext &Ctx,
15185 Expr::SideEffectsKind AllowSideEffects,
15186 EvalInfo &Info) {
15187 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15187, __extension__ __PRETTY_FUNCTION__))
;
15188 if (!E->getType()->isIntegralOrEnumerationType())
15189 return false;
15190
15191 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15192 !ExprResult.Val.isInt() ||
15193 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15194 return false;
15195
15196 return true;
15197}
15198
15199static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15200 const ASTContext &Ctx,
15201 Expr::SideEffectsKind AllowSideEffects,
15202 EvalInfo &Info) {
15203 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15203, __extension__ __PRETTY_FUNCTION__))
;
15204 if (!E->getType()->isFixedPointType())
15205 return false;
15206
15207 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15208 return false;
15209
15210 if (!ExprResult.Val.isFixedPoint() ||
15211 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15212 return false;
15213
15214 return true;
15215}
15216
15217/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15218/// any crazy technique (that has nothing to do with language standards) that
15219/// we want to. If this function returns true, it returns the folded constant
15220/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15221/// will be applied to the result.
15222bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15223 bool InConstantContext) const {
15224 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15225, __extension__ __PRETTY_FUNCTION__
))
15225 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15225, __extension__ __PRETTY_FUNCTION__
))
;
15226 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15227 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15228 Info.InConstantContext = InConstantContext;
15229 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15230}
15231
15232bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15233 bool InConstantContext) const {
15234 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
15235 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
;
15236 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15237 EvalResult Scratch;
15238 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15239 HandleConversionToBool(Scratch.Val, Result);
15240}
15241
15242bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15243 SideEffectsKind AllowSideEffects,
15244 bool InConstantContext) const {
15245 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15246, __extension__ __PRETTY_FUNCTION__
))
15246 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15246, __extension__ __PRETTY_FUNCTION__
))
;
15247 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15248 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15249 Info.InConstantContext = InConstantContext;
15250 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15251}
15252
15253bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15254 SideEffectsKind AllowSideEffects,
15255 bool InConstantContext) const {
15256 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15257, __extension__ __PRETTY_FUNCTION__
))
15257 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15257, __extension__ __PRETTY_FUNCTION__
))
;
15258 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15259 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15260 Info.InConstantContext = InConstantContext;
15261 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15262}
15263
15264bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15265 SideEffectsKind AllowSideEffects,
15266 bool InConstantContext) const {
15267 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15268, __extension__ __PRETTY_FUNCTION__
))
15268 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15268, __extension__ __PRETTY_FUNCTION__
))
;
15269
15270 if (!getType()->isRealFloatingType())
15271 return false;
15272
15273 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15274 EvalResult ExprResult;
15275 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15276 !ExprResult.Val.isFloat() ||
15277 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15278 return false;
15279
15280 Result = ExprResult.Val.getFloat();
15281 return true;
15282}
15283
15284bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15285 bool InConstantContext) const {
15286 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15287, __extension__ __PRETTY_FUNCTION__
))
15287 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15287, __extension__ __PRETTY_FUNCTION__
))
;
15288
15289 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15290 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15291 Info.InConstantContext = InConstantContext;
15292 LValue LV;
15293 CheckedTemporaries CheckedTemps;
15294 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15295 Result.HasSideEffects ||
15296 !CheckLValueConstantExpression(Info, getExprLoc(),
15297 Ctx.getLValueReferenceType(getType()), LV,
15298 ConstantExprKind::Normal, CheckedTemps))
15299 return false;
15300
15301 LV.moveInto(Result.Val);
15302 return true;
15303}
15304
15305static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15306 APValue DestroyedValue, QualType Type,
15307 SourceLocation Loc, Expr::EvalStatus &EStatus,
15308 bool IsConstantDestruction) {
15309 EvalInfo Info(Ctx, EStatus,
15310 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15311 : EvalInfo::EM_ConstantFold);
15312 Info.setEvaluatingDecl(Base, DestroyedValue,
15313 EvalInfo::EvaluatingDeclKind::Dtor);
15314 Info.InConstantContext = IsConstantDestruction;
15315
15316 LValue LVal;
15317 LVal.set(Base);
15318
15319 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15320 EStatus.HasSideEffects)
15321 return false;
15322
15323 if (!Info.discardCleanups())
15324 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15324)
;
15325
15326 return true;
15327}
15328
15329bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15330 ConstantExprKind Kind) const {
15331 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15332, __extension__ __PRETTY_FUNCTION__
))
15332 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15332, __extension__ __PRETTY_FUNCTION__
))
;
15333 bool IsConst;
15334 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15335 return true;
15336
15337 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15338 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15339 EvalInfo Info(Ctx, Result, EM);
15340 Info.InConstantContext = true;
15341
15342 // The type of the object we're initializing is 'const T' for a class NTTP.
15343 QualType T = getType();
15344 if (Kind == ConstantExprKind::ClassTemplateArgument)
15345 T.addConst();
15346
15347 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15348 // represent the result of the evaluation. CheckConstantExpression ensures
15349 // this doesn't escape.
15350 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15351 APValue::LValueBase Base(&BaseMTE);
15352
15353 Info.setEvaluatingDecl(Base, Result.Val);
15354 LValue LVal;
15355 LVal.set(Base);
15356
15357 {
15358 // C++23 [intro.execution]/p5
15359 // A full-expression is [...] a constant-expression
15360 // So we need to make sure temporary objects are destroyed after having
15361 // evaluating the expression (per C++23 [class.temporary]/p4).
15362 FullExpressionRAII Scope(Info);
15363 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15364 Result.HasSideEffects || !Scope.destroy())
15365 return false;
15366 }
15367
15368 if (!Info.discardCleanups())
15369 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15369)
;
15370
15371 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15372 Result.Val, Kind))
15373 return false;
15374 if (!CheckMemoryLeaks(Info))
15375 return false;
15376
15377 // If this is a class template argument, it's required to have constant
15378 // destruction too.
15379 if (Kind == ConstantExprKind::ClassTemplateArgument &&
15380 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15381 true) ||
15382 Result.HasSideEffects)) {
15383 // FIXME: Prefix a note to indicate that the problem is lack of constant
15384 // destruction.
15385 return false;
15386 }
15387
15388 return true;
15389}
15390
15391bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15392 const VarDecl *VD,
15393 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15394 bool IsConstantInitialization) const {
15395 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15396, __extension__ __PRETTY_FUNCTION__
))
15396 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15396, __extension__ __PRETTY_FUNCTION__
))
;
15397
15398 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15399 std::string Name;
15400 llvm::raw_string_ostream OS(Name);
15401 VD->printQualifiedName(OS);
15402 return Name;
15403 });
15404
15405 // FIXME: Evaluating initializers for large array and record types can cause
15406 // performance problems. Only do so in C++11 for now.
15407 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15408 !Ctx.getLangOpts().CPlusPlus11)
15409 return false;
15410
15411 Expr::EvalStatus EStatus;
15412 EStatus.Diag = &Notes;
15413
15414 EvalInfo Info(Ctx, EStatus,
15415 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15416 ? EvalInfo::EM_ConstantExpression
15417 : EvalInfo::EM_ConstantFold);
15418 Info.setEvaluatingDecl(VD, Value);
15419 Info.InConstantContext = IsConstantInitialization;
15420
15421 SourceLocation DeclLoc = VD->getLocation();
15422 QualType DeclTy = VD->getType();
15423
15424 if (Info.EnableNewConstInterp) {
15425 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15426 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15427 return false;
15428 } else {
15429 LValue LVal;
15430 LVal.set(VD);
15431
15432 if (!EvaluateInPlace(Value, Info, LVal, this,
15433 /*AllowNonLiteralTypes=*/true) ||
15434 EStatus.HasSideEffects)
15435 return false;
15436
15437 // At this point, any lifetime-extended temporaries are completely
15438 // initialized.
15439 Info.performLifetimeExtension();
15440
15441 if (!Info.discardCleanups())
15442 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15442)
;
15443 }
15444 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15445 ConstantExprKind::Normal) &&
15446 CheckMemoryLeaks(Info);
15447}
15448
15449bool VarDecl::evaluateDestruction(
15450 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15451 Expr::EvalStatus EStatus;
15452 EStatus.Diag = &Notes;
15453
15454 // Only treat the destruction as constant destruction if we formally have
15455 // constant initialization (or are usable in a constant expression).
15456 bool IsConstantDestruction = hasConstantInitialization();
15457
15458 // Make a copy of the value for the destructor to mutate, if we know it.
15459 // Otherwise, treat the value as default-initialized; if the destructor works
15460 // anyway, then the destruction is constant (and must be essentially empty).
15461 APValue DestroyedValue;
15462 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15463 DestroyedValue = *getEvaluatedValue();
15464 else if (!getDefaultInitValue(getType(), DestroyedValue))
15465 return false;
15466
15467 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15468 getType(), getLocation(), EStatus,
15469 IsConstantDestruction) ||
15470 EStatus.HasSideEffects)
15471 return false;
15472
15473 ensureEvaluatedStmt()->HasConstantDestruction = true;
15474 return true;
15475}
15476
15477/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15478/// constant folded, but discard the result.
15479bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15480 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15481, __extension__ __PRETTY_FUNCTION__
))
15481 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15481, __extension__ __PRETTY_FUNCTION__
))
;
15482
15483 EvalResult Result;
15484 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15485 !hasUnacceptableSideEffect(Result, SEK);
15486}
15487
15488APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15489 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15490 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15491, __extension__ __PRETTY_FUNCTION__
))
15491 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15491, __extension__ __PRETTY_FUNCTION__
))
;
15492
15493 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15494 EvalResult EVResult;
15495 EVResult.Diag = Diag;
15496 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15497 Info.InConstantContext = true;
15498
15499 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15500 (void)Result;
15501 assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression"
) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\""
, "clang/lib/AST/ExprConstant.cpp", 15501, __extension__ __PRETTY_FUNCTION__
))
;
15502 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer"
) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\""
, "clang/lib/AST/ExprConstant.cpp", 15502, __extension__ __PRETTY_FUNCTION__
))
;
15503
15504 return EVResult.Val.getInt();
15505}
15506
15507APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15508 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15509 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15510, __extension__ __PRETTY_FUNCTION__
))
15510 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15510, __extension__ __PRETTY_FUNCTION__
))
;
15511
15512 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15513 EvalResult EVResult;
15514 EVResult.Diag = Diag;
15515 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15516 Info.InConstantContext = true;
15517 Info.CheckingForUndefinedBehavior = true;
15518
15519 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15520 (void)Result;
15521 assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression"
) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\""
, "clang/lib/AST/ExprConstant.cpp", 15521, __extension__ __PRETTY_FUNCTION__
))
;
15522 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer"
) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\""
, "clang/lib/AST/ExprConstant.cpp", 15522, __extension__ __PRETTY_FUNCTION__
))
;
15523
15524 return EVResult.Val.getInt();
15525}
15526
15527void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15528 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15529, __extension__ __PRETTY_FUNCTION__
))
15529 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 15529, __extension__ __PRETTY_FUNCTION__
))
;
15530
15531 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15532 bool IsConst;
15533 EvalResult EVResult;
15534 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15535 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15536 Info.CheckingForUndefinedBehavior = true;
15537 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15538 }
15539}
15540
15541bool Expr::EvalResult::isGlobalLValue() const {
15542 assert(Val.isLValue())(static_cast <bool> (Val.isLValue()) ? void (0) : __assert_fail
("Val.isLValue()", "clang/lib/AST/ExprConstant.cpp", 15542, __extension__
__PRETTY_FUNCTION__))
;
15543 return IsGlobalLValue(Val.getLValueBase());
15544}
15545
15546/// isIntegerConstantExpr - this recursive routine will test if an expression is
15547/// an integer constant expression.
15548
15549/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15550/// comma, etc
15551
15552// CheckICE - This function does the fundamental ICE checking: the returned
15553// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15554// and a (possibly null) SourceLocation indicating the location of the problem.
15555//
15556// Note that to reduce code duplication, this helper does no evaluation
15557// itself; the caller checks whether the expression is evaluatable, and
15558// in the rare cases where CheckICE actually cares about the evaluated
15559// value, it calls into Evaluate.
15560
15561namespace {
15562
15563enum ICEKind {
15564 /// This expression is an ICE.
15565 IK_ICE,
15566 /// This expression is not an ICE, but if it isn't evaluated, it's
15567 /// a legal subexpression for an ICE. This return value is used to handle
15568 /// the comma operator in C99 mode, and non-constant subexpressions.
15569 IK_ICEIfUnevaluated,
15570 /// This expression is not an ICE, and is not a legal subexpression for one.
15571 IK_NotICE
15572};
15573
15574struct ICEDiag {
15575 ICEKind Kind;
15576 SourceLocation Loc;
15577
15578 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15579};
15580
15581}
15582
15583static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15584
15585static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15586
15587static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15588 Expr::EvalResult EVResult;
15589 Expr::EvalStatus Status;
15590 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15591
15592 Info.InConstantContext = true;
15593 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15594 !EVResult.Val.isInt())
15595 return ICEDiag(IK_NotICE, E->getBeginLoc());
15596
15597 return NoDiag();
15598}
15599
15600static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15601 assert(!E->isValueDependent() && "Should not see value dependent exprs!")(static_cast <bool> (!E->isValueDependent() &&
"Should not see value dependent exprs!") ? void (0) : __assert_fail
("!E->isValueDependent() && \"Should not see value dependent exprs!\""
, "clang/lib/AST/ExprConstant.cpp", 15601, __extension__ __PRETTY_FUNCTION__
))
;
15602 if (!E->getType()->isIntegralOrEnumerationType())
15603 return ICEDiag(IK_NotICE, E->getBeginLoc());
15604
15605 switch (E->getStmtClass()) {
15606#define ABSTRACT_STMT(Node)
15607#define STMT(Node, Base) case Expr::Node##Class:
15608#define EXPR(Node, Base)
15609#include "clang/AST/StmtNodes.inc"
15610 case Expr::PredefinedExprClass:
15611 case Expr::FloatingLiteralClass:
15612 case Expr::ImaginaryLiteralClass:
15613 case Expr::StringLiteralClass:
15614 case Expr::ArraySubscriptExprClass:
15615 case Expr::MatrixSubscriptExprClass:
15616 case Expr::OMPArraySectionExprClass:
15617 case Expr::OMPArrayShapingExprClass:
15618 case Expr::OMPIteratorExprClass:
15619 case Expr::MemberExprClass:
15620 case Expr::CompoundAssignOperatorClass:
15621 case Expr::CompoundLiteralExprClass:
15622 case Expr::ExtVectorElementExprClass:
15623 case Expr::DesignatedInitExprClass:
15624 case Expr::ArrayInitLoopExprClass:
15625 case Expr::ArrayInitIndexExprClass:
15626 case Expr::NoInitExprClass:
15627 case Expr::DesignatedInitUpdateExprClass:
15628 case Expr::ImplicitValueInitExprClass:
15629 case Expr::ParenListExprClass:
15630 case Expr::VAArgExprClass:
15631 case Expr::AddrLabelExprClass:
15632 case Expr::StmtExprClass:
15633 case Expr::CXXMemberCallExprClass:
15634 case Expr::CUDAKernelCallExprClass:
15635 case Expr::CXXAddrspaceCastExprClass:
15636 case Expr::CXXDynamicCastExprClass:
15637 case Expr::CXXTypeidExprClass:
15638 case Expr::CXXUuidofExprClass:
15639 case Expr::MSPropertyRefExprClass:
15640 case Expr::MSPropertySubscriptExprClass:
15641 case Expr::CXXNullPtrLiteralExprClass:
15642 case Expr::UserDefinedLiteralClass:
15643 case Expr::CXXThisExprClass:
15644 case Expr::CXXThrowExprClass:
15645 case Expr::CXXNewExprClass:
15646 case Expr::CXXDeleteExprClass:
15647 case Expr::CXXPseudoDestructorExprClass:
15648 case Expr::UnresolvedLookupExprClass:
15649 case Expr::TypoExprClass:
15650 case Expr::RecoveryExprClass:
15651 case Expr::DependentScopeDeclRefExprClass:
15652 case Expr::CXXConstructExprClass:
15653 case Expr::CXXInheritedCtorInitExprClass:
15654 case Expr::CXXStdInitializerListExprClass:
15655 case Expr::CXXBindTemporaryExprClass:
15656 case Expr::ExprWithCleanupsClass:
15657 case Expr::CXXTemporaryObjectExprClass:
15658 case Expr::CXXUnresolvedConstructExprClass:
15659 case Expr::CXXDependentScopeMemberExprClass:
15660 case Expr::UnresolvedMemberExprClass:
15661 case Expr::ObjCStringLiteralClass:
15662 case Expr::ObjCBoxedExprClass:
15663 case Expr::ObjCArrayLiteralClass:
15664 case Expr::ObjCDictionaryLiteralClass:
15665 case Expr::ObjCEncodeExprClass:
15666 case Expr::ObjCMessageExprClass:
15667 case Expr::ObjCSelectorExprClass:
15668 case Expr::ObjCProtocolExprClass:
15669 case Expr::ObjCIvarRefExprClass:
15670 case Expr::ObjCPropertyRefExprClass:
15671 case Expr::ObjCSubscriptRefExprClass:
15672 case Expr::ObjCIsaExprClass:
15673 case Expr::ObjCAvailabilityCheckExprClass:
15674 case Expr::ShuffleVectorExprClass:
15675 case Expr::ConvertVectorExprClass:
15676 case Expr::BlockExprClass:
15677 case Expr::NoStmtClass:
15678 case Expr::OpaqueValueExprClass:
15679 case Expr::PackExpansionExprClass:
15680 case Expr::SubstNonTypeTemplateParmPackExprClass:
15681 case Expr::FunctionParmPackExprClass:
15682 case Expr::AsTypeExprClass:
15683 case Expr::ObjCIndirectCopyRestoreExprClass:
15684 case Expr::MaterializeTemporaryExprClass:
15685 case Expr::PseudoObjectExprClass:
15686 case Expr::AtomicExprClass:
15687 case Expr::LambdaExprClass:
15688 case Expr::CXXFoldExprClass:
15689 case Expr::CoawaitExprClass:
15690 case Expr::DependentCoawaitExprClass:
15691 case Expr::CoyieldExprClass:
15692 case Expr::SYCLUniqueStableNameExprClass:
15693 case Expr::CXXParenListInitExprClass:
15694 return ICEDiag(IK_NotICE, E->getBeginLoc());
15695
15696 case Expr::InitListExprClass: {
15697 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15698 // form "T x = { a };" is equivalent to "T x = a;".
15699 // Unless we're initializing a reference, T is a scalar as it is known to be
15700 // of integral or enumeration type.
15701 if (E->isPRValue())
15702 if (cast<InitListExpr>(E)->getNumInits() == 1)
15703 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15704 return ICEDiag(IK_NotICE, E->getBeginLoc());
15705 }
15706
15707 case Expr::SizeOfPackExprClass:
15708 case Expr::GNUNullExprClass:
15709 case Expr::SourceLocExprClass:
15710 return NoDiag();
15711
15712 case Expr::SubstNonTypeTemplateParmExprClass:
15713 return
15714 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15715
15716 case Expr::ConstantExprClass:
15717 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15718
15719 case Expr::ParenExprClass:
15720 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15721 case Expr::GenericSelectionExprClass:
15722 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15723 case Expr::IntegerLiteralClass:
15724 case Expr::FixedPointLiteralClass:
15725 case Expr::CharacterLiteralClass:
15726 case Expr::ObjCBoolLiteralExprClass:
15727 case Expr::CXXBoolLiteralExprClass:
15728 case Expr::CXXScalarValueInitExprClass:
15729 case Expr::TypeTraitExprClass:
15730 case Expr::ConceptSpecializationExprClass:
15731 case Expr::RequiresExprClass:
15732 case Expr::ArrayTypeTraitExprClass:
15733 case Expr::ExpressionTraitExprClass:
15734 case Expr::CXXNoexceptExprClass:
15735 return NoDiag();
15736 case Expr::CallExprClass:
15737 case Expr::CXXOperatorCallExprClass: {
15738 // C99 6.6/3 allows function calls within unevaluated subexpressions of
15739 // constant expressions, but they can never be ICEs because an ICE cannot
15740 // contain an operand of (pointer to) function type.
15741 const CallExpr *CE = cast<CallExpr>(E);
15742 if (CE->getBuiltinCallee())
15743 return CheckEvalInICE(E, Ctx);
15744 return ICEDiag(IK_NotICE, E->getBeginLoc());
15745 }
15746 case Expr::CXXRewrittenBinaryOperatorClass:
15747 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15748 Ctx);
15749 case Expr::DeclRefExprClass: {
15750 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15751 if (isa<EnumConstantDecl>(D))
15752 return NoDiag();
15753
15754 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15755 // integer variables in constant expressions:
15756 //
15757 // C++ 7.1.5.1p2
15758 // A variable of non-volatile const-qualified integral or enumeration
15759 // type initialized by an ICE can be used in ICEs.
15760 //
15761 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15762 // that mode, use of reference variables should not be allowed.
15763 const VarDecl *VD = dyn_cast<VarDecl>(D);
15764 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15765 !VD->getType()->isReferenceType())
15766 return NoDiag();
15767
15768 return ICEDiag(IK_NotICE, E->getBeginLoc());
15769 }
15770 case Expr::UnaryOperatorClass: {
15771 const UnaryOperator *Exp = cast<UnaryOperator>(E);
15772 switch (Exp->getOpcode()) {
15773 case UO_PostInc:
15774 case UO_PostDec:
15775 case UO_PreInc:
15776 case UO_PreDec:
15777 case UO_AddrOf:
15778 case UO_Deref:
15779 case UO_Coawait:
15780 // C99 6.6/3 allows increment and decrement within unevaluated
15781 // subexpressions of constant expressions, but they can never be ICEs
15782 // because an ICE cannot contain an lvalue operand.
15783 return ICEDiag(IK_NotICE, E->getBeginLoc());
15784 case UO_Extension:
15785 case UO_LNot:
15786 case UO_Plus:
15787 case UO_Minus:
15788 case UO_Not:
15789 case UO_Real:
15790 case UO_Imag:
15791 return CheckICE(Exp->getSubExpr(), Ctx);
15792 }
15793 llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class"
, "clang/lib/AST/ExprConstant.cpp", 15793)
;
15794 }
15795 case Expr::OffsetOfExprClass: {
15796 // Note that per C99, offsetof must be an ICE. And AFAIK, using
15797 // EvaluateAsRValue matches the proposed gcc behavior for cases like
15798 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
15799 // compliance: we should warn earlier for offsetof expressions with
15800 // array subscripts that aren't ICEs, and if the array subscripts
15801 // are ICEs, the value of the offsetof must be an integer constant.
15802 return CheckEvalInICE(E, Ctx);
15803 }
15804 case Expr::UnaryExprOrTypeTraitExprClass: {
15805 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15806 if ((Exp->getKind() == UETT_SizeOf) &&
15807 Exp->getTypeOfArgument()->isVariableArrayType())
15808 return ICEDiag(IK_NotICE, E->getBeginLoc());
15809 return NoDiag();
15810 }
15811 case Expr::BinaryOperatorClass: {
15812 const BinaryOperator *Exp = cast<BinaryOperator>(E);
15813 switch (Exp->getOpcode()) {
15814 case BO_PtrMemD:
15815 case BO_PtrMemI:
15816 case BO_Assign:
15817 case BO_MulAssign:
15818 case BO_DivAssign:
15819 case BO_RemAssign:
15820 case BO_AddAssign:
15821 case BO_SubAssign:
15822 case BO_ShlAssign:
15823 case BO_ShrAssign:
15824 case BO_AndAssign:
15825 case BO_XorAssign:
15826 case BO_OrAssign:
15827 // C99 6.6/3 allows assignments within unevaluated subexpressions of
15828 // constant expressions, but they can never be ICEs because an ICE cannot
15829 // contain an lvalue operand.
15830 return ICEDiag(IK_NotICE, E->getBeginLoc());
15831
15832 case BO_Mul:
15833 case BO_Div:
15834 case BO_Rem:
15835 case BO_Add:
15836 case BO_Sub:
15837 case BO_Shl:
15838 case BO_Shr:
15839 case BO_LT:
15840 case BO_GT:
15841 case BO_LE:
15842 case BO_GE:
15843 case BO_EQ:
15844 case BO_NE:
15845 case BO_And:
15846 case BO_Xor:
15847 case BO_Or:
15848 case BO_Comma:
15849 case BO_Cmp: {
15850 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15851 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15852 if (Exp->getOpcode() == BO_Div ||
15853 Exp->getOpcode() == BO_Rem) {
15854 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15855 // we don't evaluate one.
15856 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15857 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15858 if (REval == 0)
15859 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15860 if (REval.isSigned() && REval.isAllOnes()) {
15861 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15862 if (LEval.isMinSignedValue())
15863 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15864 }
15865 }
15866 }
15867 if (Exp->getOpcode() == BO_Comma) {
15868 if (Ctx.getLangOpts().C99) {
15869 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15870 // if it isn't evaluated.
15871 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15872 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15873 } else {
15874 // In both C89 and C++, commas in ICEs are illegal.
15875 return ICEDiag(IK_NotICE, E->getBeginLoc());
15876 }
15877 }
15878 return Worst(LHSResult, RHSResult);
15879 }
15880 case BO_LAnd:
15881 case BO_LOr: {
15882 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15883 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15884 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15885 // Rare case where the RHS has a comma "side-effect"; we need
15886 // to actually check the condition to see whether the side
15887 // with the comma is evaluated.
15888 if ((Exp->getOpcode() == BO_LAnd) !=
15889 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15890 return RHSResult;
15891 return NoDiag();
15892 }
15893
15894 return Worst(LHSResult, RHSResult);
15895 }
15896 }
15897 llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind"
, "clang/lib/AST/ExprConstant.cpp", 15897)
;
15898 }
15899 case Expr::ImplicitCastExprClass:
15900 case Expr::CStyleCastExprClass:
15901 case Expr::CXXFunctionalCastExprClass:
15902 case Expr::CXXStaticCastExprClass:
15903 case Expr::CXXReinterpretCastExprClass:
15904 case Expr::CXXConstCastExprClass:
15905 case Expr::ObjCBridgedCastExprClass: {
15906 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15907 if (isa<ExplicitCastExpr>(E)) {
15908 if (const FloatingLiteral *FL
15909 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15910 unsigned DestWidth = Ctx.getIntWidth(E->getType());
15911 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15912 APSInt IgnoredVal(DestWidth, !DestSigned);
15913 bool Ignored;
15914 // If the value does not fit in the destination type, the behavior is
15915 // undefined, so we are not required to treat it as a constant
15916 // expression.
15917 if (FL->getValue().convertToInteger(IgnoredVal,
15918 llvm::APFloat::rmTowardZero,
15919 &Ignored) & APFloat::opInvalidOp)
15920 return ICEDiag(IK_NotICE, E->getBeginLoc());
15921 return NoDiag();
15922 }
15923 }
15924 switch (cast<CastExpr>(E)->getCastKind()) {
15925 case CK_LValueToRValue:
15926 case CK_AtomicToNonAtomic:
15927 case CK_NonAtomicToAtomic:
15928 case CK_NoOp:
15929 case CK_IntegralToBoolean:
15930 case CK_IntegralCast:
15931 return CheckICE(SubExpr, Ctx);
15932 default:
15933 return ICEDiag(IK_NotICE, E->getBeginLoc());
15934 }
15935 }
15936 case Expr::BinaryConditionalOperatorClass: {
15937 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15938 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15939 if (CommonResult.Kind == IK_NotICE) return CommonResult;
15940 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15941 if (FalseResult.Kind == IK_NotICE) return FalseResult;
15942 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15943 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15944 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15945 return FalseResult;
15946 }
15947 case Expr::ConditionalOperatorClass: {
15948 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15949 // If the condition (ignoring parens) is a __builtin_constant_p call,
15950 // then only the true side is actually considered in an integer constant
15951 // expression, and it is fully evaluated. This is an important GNU
15952 // extension. See GCC PR38377 for discussion.
15953 if (const CallExpr *CallCE
15954 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15955 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15956 return CheckEvalInICE(E, Ctx);
15957 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15958 if (CondResult.Kind == IK_NotICE)
15959 return CondResult;
15960
15961 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15962 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15963
15964 if (TrueResult.Kind == IK_NotICE)
15965 return TrueResult;
15966 if (FalseResult.Kind == IK_NotICE)
15967 return FalseResult;
15968 if (CondResult.Kind == IK_ICEIfUnevaluated)
15969 return CondResult;
15970 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15971 return NoDiag();
15972 // Rare case where the diagnostics depend on which side is evaluated
15973 // Note that if we get here, CondResult is 0, and at least one of
15974 // TrueResult and FalseResult is non-zero.
15975 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15976 return FalseResult;
15977 return TrueResult;
15978 }
15979 case Expr::CXXDefaultArgExprClass:
15980 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15981 case Expr::CXXDefaultInitExprClass:
15982 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15983 case Expr::ChooseExprClass: {
15984 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15985 }
15986 case Expr::BuiltinBitCastExprClass: {
15987 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15988 return ICEDiag(IK_NotICE, E->getBeginLoc());
15989 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15990 }
15991 }
15992
15993 llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "clang/lib/AST/ExprConstant.cpp"
, 15993)
;
15994}
15995
15996/// Evaluate an expression as a C++11 integral constant expression.
15997static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15998 const Expr *E,
15999 llvm::APSInt *Value,
16000 SourceLocation *Loc) {
16001 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16002 if (Loc) *Loc = E->getExprLoc();
16003 return false;
16004 }
16005
16006 APValue Result;
16007 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16008 return false;
16009
16010 if (!Result.isInt()) {
16011 if (Loc) *Loc = E->getExprLoc();
16012 return false;
16013 }
16014
16015 if (Value) *Value = Result.getInt();
16016 return true;
16017}
16018
16019bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16020 SourceLocation *Loc) const {
16021 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16022, __extension__ __PRETTY_FUNCTION__
))
16022 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16022, __extension__ __PRETTY_FUNCTION__
))
;
16023
16024 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16025
16026 if (Ctx.getLangOpts().CPlusPlus11)
16027 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16028
16029 ICEDiag D = CheckICE(this, Ctx);
16030 if (D.Kind != IK_ICE) {
16031 if (Loc) *Loc = D.Loc;
16032 return false;
16033 }
16034 return true;
16035}
16036
16037std::optional<llvm::APSInt>
16038Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
16039 bool isEvaluated) const {
16040 if (isValueDependent()) {
16041 // Expression evaluator can't succeed on a dependent expression.
16042 return std::nullopt;
16043 }
16044
16045 APSInt Value;
16046
16047 if (Ctx.getLangOpts().CPlusPlus11) {
16048 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16049 return Value;
16050 return std::nullopt;
16051 }
16052
16053 if (!isIntegerConstantExpr(Ctx, Loc))
16054 return std::nullopt;
16055
16056 // The only possible side-effects here are due to UB discovered in the
16057 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16058 // required to treat the expression as an ICE, so we produce the folded
16059 // value.
16060 EvalResult ExprResult;
16061 Expr::EvalStatus Status;
16062 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16063 Info.InConstantContext = true;
16064
16065 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16066 llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!",
"clang/lib/AST/ExprConstant.cpp", 16066)
;
16067
16068 return ExprResult.Val.getInt();
16069}
16070
16071bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16072 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16073, __extension__ __PRETTY_FUNCTION__
))
16073 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16073, __extension__ __PRETTY_FUNCTION__
))
;
16074
16075 return CheckICE(this, Ctx).Kind == IK_ICE;
16076}
16077
16078bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16079 SourceLocation *Loc) const {
16080 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16081, __extension__ __PRETTY_FUNCTION__
))
16081 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16081, __extension__ __PRETTY_FUNCTION__
))
;
16082
16083 // We support this checking in C++98 mode in order to diagnose compatibility
16084 // issues.
16085 assert(Ctx.getLangOpts().CPlusPlus)(static_cast <bool> (Ctx.getLangOpts().CPlusPlus) ? void
(0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "clang/lib/AST/ExprConstant.cpp"
, 16085, __extension__ __PRETTY_FUNCTION__))
;
16086
16087 // Build evaluation settings.
16088 Expr::EvalStatus Status;
16089 SmallVector<PartialDiagnosticAt, 8> Diags;
16090 Status.Diag = &Diags;
16091 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16092
16093 APValue Scratch;
16094 bool IsConstExpr =
16095 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16096 // FIXME: We don't produce a diagnostic for this, but the callers that
16097 // call us on arbitrary full-expressions should generally not care.
16098 Info.discardCleanups() && !Status.HasSideEffects;
16099
16100 if (!Diags.empty()) {
16101 IsConstExpr = false;
16102 if (Loc) *Loc = Diags[0].first;
16103 } else if (!IsConstExpr) {
16104 // FIXME: This shouldn't happen.
16105 if (Loc) *Loc = getExprLoc();
16106 }
16107
16108 return IsConstExpr;
16109}
16110
16111bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16112 const FunctionDecl *Callee,
16113 ArrayRef<const Expr*> Args,
16114 const Expr *This) const {
16115 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16116, __extension__ __PRETTY_FUNCTION__
))
16116 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16116, __extension__ __PRETTY_FUNCTION__
))
;
16117
16118 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16119 std::string Name;
16120 llvm::raw_string_ostream OS(Name);
16121 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16122 /*Qualified=*/true);
16123 return Name;
16124 });
16125
16126 Expr::EvalStatus Status;
16127 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16128 Info.InConstantContext = true;
16129
16130 LValue ThisVal;
16131 const LValue *ThisPtr = nullptr;
16132 if (This) {
16133#ifndef NDEBUG
16134 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16135 assert(MD && "Don't provide `this` for non-methods.")(static_cast <bool> (MD && "Don't provide `this` for non-methods."
) ? void (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\""
, "clang/lib/AST/ExprConstant.cpp", 16135, __extension__ __PRETTY_FUNCTION__
))
;
16136 assert(!MD->isStatic() && "Don't provide `this` for static methods.")(static_cast <bool> (!MD->isStatic() && "Don't provide `this` for static methods."
) ? void (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\""
, "clang/lib/AST/ExprConstant.cpp", 16136, __extension__ __PRETTY_FUNCTION__
))
;
16137#endif
16138 if (!This->isValueDependent() &&
16139 EvaluateObjectArgument(Info, This, ThisVal) &&
16140 !Info.EvalStatus.HasSideEffects)
16141 ThisPtr = &ThisVal;
16142
16143 // Ignore any side-effects from a failed evaluation. This is safe because
16144 // they can't interfere with any other argument evaluation.
16145 Info.EvalStatus.HasSideEffects = false;
16146 }
16147
16148 CallRef Call = Info.CurrentCall->createCall(Callee);
16149 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16150 I != E; ++I) {
16151 unsigned Idx = I - Args.begin();
16152 if (Idx >= Callee->getNumParams())
16153 break;
16154 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16155 if ((*I)->isValueDependent() ||
16156 !EvaluateCallArg(PVD, *I, Call, Info) ||
16157 Info.EvalStatus.HasSideEffects) {
16158 // If evaluation fails, throw away the argument entirely.
16159 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16160 *Slot = APValue();
16161 }
16162
16163 // Ignore any side-effects from a failed evaluation. This is safe because
16164 // they can't interfere with any other argument evaluation.
16165 Info.EvalStatus.HasSideEffects = false;
16166 }
16167
16168 // Parameter cleanups happen in the caller and are not part of this
16169 // evaluation.
16170 Info.discardCleanups();
16171 Info.EvalStatus.HasSideEffects = false;
16172
16173 // Build fake call to Callee.
16174 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16175 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16176 FullExpressionRAII Scope(Info);
16177 return Evaluate(Value, Info, this) && Scope.destroy() &&
16178 !Info.EvalStatus.HasSideEffects;
16179}
16180
16181bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16182 SmallVectorImpl<
16183 PartialDiagnosticAt> &Diags) {
16184 // FIXME: It would be useful to check constexpr function templates, but at the
16185 // moment the constant expression evaluator cannot cope with the non-rigorous
16186 // ASTs which we build for dependent expressions.
16187 if (FD->isDependentContext())
16188 return true;
16189
16190 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16191 std::string Name;
16192 llvm::raw_string_ostream OS(Name);
16193 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16194 /*Qualified=*/true);
16195 return Name;
16196 });
16197
16198 Expr::EvalStatus Status;
16199 Status.Diag = &Diags;
16200
16201 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16202 Info.InConstantContext = true;
16203 Info.CheckingPotentialConstantExpression = true;
16204
16205 // The constexpr VM attempts to compile all methods to bytecode here.
16206 if (Info.EnableNewConstInterp) {
16207 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16208 return Diags.empty();
16209 }
16210
16211 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16212 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16213
16214 // Fabricate an arbitrary expression on the stack and pretend that it
16215 // is a temporary being used as the 'this' pointer.
16216 LValue This;
16217 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16218 This.set({&VIE, Info.CurrentCall->Index});
16219
16220 ArrayRef<const Expr*> Args;
16221
16222 APValue Scratch;
16223 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16224 // Evaluate the call as a constant initializer, to allow the construction
16225 // of objects of non-literal types.
16226 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16227 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16228 } else {
16229 SourceLocation Loc = FD->getLocation();
16230 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16231 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16232 }
16233
16234 return Diags.empty();
16235}
16236
16237bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16238 const FunctionDecl *FD,
16239 SmallVectorImpl<
16240 PartialDiagnosticAt> &Diags) {
16241 assert(!E->isValueDependent() &&(static_cast <bool> (!E->isValueDependent() &&
"Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16242, __extension__ __PRETTY_FUNCTION__
))
16242 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!E->isValueDependent() &&
"Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "clang/lib/AST/ExprConstant.cpp", 16242, __extension__ __PRETTY_FUNCTION__
))
;
16243
16244 Expr::EvalStatus Status;
16245 Status.Diag = &Diags;
16246
16247 EvalInfo Info(FD->getASTContext(), Status,
16248 EvalInfo::EM_ConstantExpressionUnevaluated);
16249 Info.InConstantContext = true;
16250 Info.CheckingPotentialConstantExpression = true;
16251
16252 // Fabricate a call stack frame to give the arguments a plausible cover story.
16253 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16254
16255 APValue ResultScratch;
16256 Evaluate(ResultScratch, Info, E);
16257 return Diags.empty();
16258}
16259
16260bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16261 unsigned Type) const {
16262 if (!getType()->isPointerType())
16263 return false;
16264
16265 Expr::EvalStatus Status;
16266 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16267 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16268}
16269
16270static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16271 EvalInfo &Info) {
16272 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16273 return false;
16274
16275 LValue String;
16276
16277 if (!EvaluatePointer(E, String, Info))
16278 return false;
16279
16280 QualType CharTy = E->getType()->getPointeeType();
16281
16282 // Fast path: if it's a string literal, search the string value.
16283 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16284 String.getLValueBase().dyn_cast<const Expr *>())) {
16285 StringRef Str = S->getBytes();
16286 int64_t Off = String.Offset.getQuantity();
16287 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16288 S->getCharByteWidth() == 1 &&
16289 // FIXME: Add fast-path for wchar_t too.
16290 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16291 Str = Str.substr(Off);
16292
16293 StringRef::size_type Pos = Str.find(0);
16294 if (Pos != StringRef::npos)
16295 Str = Str.substr(0, Pos);
16296
16297 Result = Str.size();
16298 return true;
16299 }
16300
16301 // Fall through to slow path.
16302 }
16303
16304 // Slow path: scan the bytes of the string looking for the terminating 0.
16305 for (uint64_t Strlen = 0; /**/; ++Strlen) {
16306 APValue Char;
16307 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16308 !Char.isInt())
16309 return false;
16310 if (!Char.getInt()) {
16311 Result = Strlen;
16312 return true;
16313 }
16314 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16315 return false;
16316 }
16317}
16318
16319bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16320 Expr::EvalStatus Status;
16321 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16322 return EvaluateBuiltinStrLen(this, Result, Info);
16323}