Bug Summary

File:build/source/clang/lib/AST/ExprConstant.cpp
Warning:line 3206, column 27
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16 -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 CLANG_REPOSITORY_STRING="++20230110111228+ff8e0ed9308c-1~exp1~20230110111316.1024" -D _DEBUG -D _GNU_SOURCE -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-16/lib/clang/16/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/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1673349197 -O2 -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/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -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-01-10-180417-16238-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/Optional.h"
56#include "llvm/ADT/SmallBitVector.h"
57#include "llvm/Support/Debug.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/raw_ostream.h"
61#include <cstring>
62#include <functional>
63#include <optional>
64
65#define DEBUG_TYPE"exprconstant" "exprconstant"
66
67using namespace clang;
68using llvm::APFixedPoint;
69using llvm::APInt;
70using llvm::APSInt;
71using llvm::APFloat;
72using llvm::FixedPointSemantics;
73using llvm::Optional;
74
75namespace {
76 struct LValue;
77 class CallStackFrame;
78 class EvalInfo;
79
80 using SourceLocExprScopeGuard =
81 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
82
83 static QualType getType(APValue::LValueBase B) {
84 return B.getType();
85 }
86
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field declaration.
89 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
90 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
91 }
92 /// Get an LValue path entry, which is known to not be an array index, as a
93 /// base class declaration.
94 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
95 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
96 }
97 /// Determine whether this LValue path entry for a base class names a virtual
98 /// base class.
99 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
100 return E.getAsBaseOrMember().getInt();
101 }
102
103 /// Given an expression, determine the type used to store the result of
104 /// evaluating that expression.
105 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
106 if (E->isPRValue())
107 return E->getType();
108 return Ctx.getLValueReferenceType(E->getType());
109 }
110
111 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
112 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
113 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
114 return DirectCallee->getAttr<AllocSizeAttr>();
115 if (const Decl *IndirectCallee = CE->getCalleeDecl())
116 return IndirectCallee->getAttr<AllocSizeAttr>();
117 return nullptr;
118 }
119
120 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
121 /// This will look through a single cast.
122 ///
123 /// Returns null if we couldn't unwrap a function with alloc_size.
124 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
125 if (!E->getType()->isPointerType())
126 return nullptr;
127
128 E = E->IgnoreParens();
129 // If we're doing a variable assignment from e.g. malloc(N), there will
130 // probably be a cast of some kind. In exotic cases, we might also see a
131 // top-level ExprWithCleanups. Ignore them either way.
132 if (const auto *FE = dyn_cast<FullExpr>(E))
133 E = FE->getSubExpr()->IgnoreParens();
134
135 if (const auto *Cast = dyn_cast<CastExpr>(E))
136 E = Cast->getSubExpr()->IgnoreParens();
137
138 if (const auto *CE = dyn_cast<CallExpr>(E))
139 return getAllocSizeAttr(CE) ? CE : nullptr;
140 return nullptr;
141 }
142
143 /// Determines whether or not the given Base contains a call to a function
144 /// with the alloc_size attribute.
145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146 const auto *E = Base.dyn_cast<const Expr *>();
147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
148 }
149
150 /// Determines whether the given kind of constant expression is only ever
151 /// used for name mangling. If so, it's permitted to reference things that we
152 /// can't generate code for (in particular, dllimported functions).
153 static bool isForManglingOnly(ConstantExprKind Kind) {
154 switch (Kind) {
155 case ConstantExprKind::Normal:
156 case ConstantExprKind::ClassTemplateArgument:
157 case ConstantExprKind::ImmediateInvocation:
158 // Note that non-type template arguments of class type are emitted as
159 // template parameter objects.
160 return false;
161
162 case ConstantExprKind::NonClassTemplateArgument:
163 return true;
164 }
165 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 165)
;
166 }
167
168 static bool isTemplateArgument(ConstantExprKind Kind) {
169 switch (Kind) {
170 case ConstantExprKind::Normal:
171 case ConstantExprKind::ImmediateInvocation:
172 return false;
173
174 case ConstantExprKind::ClassTemplateArgument:
175 case ConstantExprKind::NonClassTemplateArgument:
176 return true;
177 }
178 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 178)
;
179 }
180
181 /// The bound to claim that an array of unknown bound has.
182 /// The value in MostDerivedArraySize is undefined in this case. So, set it
183 /// to an arbitrary value that's likely to loudly break things if it's used.
184 static const uint64_t AssumedSizeForUnsizedArray =
185 std::numeric_limits<uint64_t>::max() / 2;
186
187 /// Determines if an LValue with the given LValueBase will have an unsized
188 /// array in its designator.
189 /// Find the path length and type of the most-derived subobject in the given
190 /// path, and find the size of the containing array, if any.
191 static unsigned
192 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
193 ArrayRef<APValue::LValuePathEntry> Path,
194 uint64_t &ArraySize, QualType &Type, bool &IsArray,
195 bool &FirstEntryIsUnsizedArray) {
196 // This only accepts LValueBases from APValues, and APValues don't support
197 // arrays that lack size info.
198 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", 199, __extension__ __PRETTY_FUNCTION__
))
199 "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", 199, __extension__ __PRETTY_FUNCTION__
))
;
200 unsigned MostDerivedLength = 0;
201 Type = getType(Base);
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getSize().getZExtValue();
212 } else {
213 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", 213, __extension__ __PRETTY_FUNCTION__
))
;
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const FieldDecl *FD = getAsField(Path[I])) {
224 Type = FD->getType();
225 ArraySize = 0;
226 MostDerivedLength = I + 1;
227 IsArray = false;
228 } else {
229 // Path[I] describes a base class.
230 ArraySize = 0;
231 IsArray = false;
232 }
233 }
234 return MostDerivedLength;
235 }
236
237 /// A path from a glvalue to a subobject of that glvalue.
238 struct SubobjectDesignator {
239 /// True if the subobject was named in a manner not supported by C++11. Such
240 /// lvalues can still be folded, but they are not core constant expressions
241 /// and we cannot perform lvalue-to-rvalue conversions on them.
242 unsigned Invalid : 1;
243
244 /// Is this a pointer one past the end of an object?
245 unsigned IsOnePastTheEnd : 1;
246
247 /// Indicator of whether the first entry is an unsized array.
248 unsigned FirstEntryIsAnUnsizedArray : 1;
249
250 /// Indicator of whether the most-derived object is an array element.
251 unsigned MostDerivedIsArrayElement : 1;
252
253 /// The length of the path to the most-derived object of which this is a
254 /// subobject.
255 unsigned MostDerivedPathLength : 28;
256
257 /// The size of the array of which the most-derived object is an element.
258 /// This will always be 0 if the most-derived object is not an array
259 /// element. 0 is not an indicator of whether or not the most-derived object
260 /// is an array, however, because 0-length arrays are allowed.
261 ///
262 /// If the current array is an unsized array, the value of this is
263 /// undefined.
264 uint64_t MostDerivedArraySize;
265
266 /// The type of the most derived object referred to by this address.
267 QualType MostDerivedType;
268
269 typedef APValue::LValuePathEntry PathEntry;
270
271 /// The entries on the path from the glvalue to the designated subobject.
272 SmallVector<PathEntry, 8> Entries;
273
274 SubobjectDesignator() : Invalid(true) {}
275
276 explicit SubobjectDesignator(QualType T)
277 : Invalid(false), IsOnePastTheEnd(false),
278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279 MostDerivedPathLength(0), MostDerivedArraySize(0),
280 MostDerivedType(T) {}
281
282 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
283 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
285 MostDerivedPathLength(0), MostDerivedArraySize(0) {
286 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", 286, __extension__ __PRETTY_FUNCTION__
))
;
287 if (!Invalid) {
288 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
289 ArrayRef<PathEntry> VEntries = V.getLValuePath();
290 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
291 if (V.getLValueBase()) {
292 bool IsArray = false;
293 bool FirstIsUnsizedArray = false;
294 MostDerivedPathLength = findMostDerivedSubobject(
295 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
296 MostDerivedType, IsArray, FirstIsUnsizedArray);
297 MostDerivedIsArrayElement = IsArray;
298 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
299 }
300 }
301 }
302
303 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
304 unsigned NewLength) {
305 if (Invalid)
306 return;
307
308 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", 308, __extension__ __PRETTY_FUNCTION__
))
;
309 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", 309, __extension__ __PRETTY_FUNCTION__
))
;
310
311 if (NewLength == Entries.size())
312 return;
313 Entries.resize(NewLength);
314
315 bool IsArray = false;
316 bool FirstIsUnsizedArray = false;
317 MostDerivedPathLength = findMostDerivedSubobject(
318 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
319 FirstIsUnsizedArray);
320 MostDerivedIsArrayElement = IsArray;
321 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
322 }
323
324 void setInvalid() {
325 Invalid = true;
326 Entries.clear();
327 }
328
329 /// Determine whether the most derived subobject is an array without a
330 /// known bound.
331 bool isMostDerivedAnUnsizedArray() const {
332 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", 332, __extension__ __PRETTY_FUNCTION__
))
;
333 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
334 }
335
336 /// Determine what the most derived array's size is. Results in an assertion
337 /// failure if the most derived array lacks a size.
338 uint64_t getMostDerivedArraySize() const {
339 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", 339, __extension__ __PRETTY_FUNCTION__
))
;
340 return MostDerivedArraySize;
341 }
342
343 /// Determine whether this is a one-past-the-end pointer.
344 bool isOnePastTheEnd() const {
345 assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail
("!Invalid", "clang/lib/AST/ExprConstant.cpp", 345, __extension__
__PRETTY_FUNCTION__))
;
346 if (IsOnePastTheEnd)
347 return true;
348 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
349 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
350 MostDerivedArraySize)
351 return true;
352 return false;
353 }
354
355 /// Get the range of valid index adjustments in the form
356 /// {maximum value that can be subtracted from this pointer,
357 /// maximum value that can be added to this pointer}
358 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
359 if (Invalid || isMostDerivedAnUnsizedArray())
360 return {0, 0};
361
362 // [expr.add]p4: For the purposes of these operators, a pointer to a
363 // nonarray object behaves the same as a pointer to the first element of
364 // an array of length one with the type of the object as its element type.
365 bool IsArray = MostDerivedPathLength == Entries.size() &&
366 MostDerivedIsArrayElement;
367 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
368 : (uint64_t)IsOnePastTheEnd;
369 uint64_t ArraySize =
370 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
371 return {ArrayIndex, ArraySize - ArrayIndex};
372 }
373
374 /// Check that this refers to a valid subobject.
375 bool isValidSubobject() const {
376 if (Invalid)
377 return false;
378 return !isOnePastTheEnd();
379 }
380 /// Check that this refers to a valid subobject, and if not, produce a
381 /// relevant diagnostic and set the designator as invalid.
382 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
383
384 /// Get the type of the designated object.
385 QualType getType(ASTContext &Ctx) const {
386 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", 386, __extension__ __PRETTY_FUNCTION__
))
;
387 return MostDerivedPathLength == Entries.size()
388 ? MostDerivedType
389 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
390 }
391
392 /// Update this designator to refer to the first element within this array.
393 void addArrayUnchecked(const ConstantArrayType *CAT) {
394 Entries.push_back(PathEntry::ArrayIndex(0));
395
396 // This is a most-derived object.
397 MostDerivedType = CAT->getElementType();
398 MostDerivedIsArrayElement = true;
399 MostDerivedArraySize = CAT->getSize().getZExtValue();
400 MostDerivedPathLength = Entries.size();
401 }
402 /// Update this designator to refer to the first element within the array of
403 /// elements of type T. This is an array of unknown size.
404 void addUnsizedArrayUnchecked(QualType ElemTy) {
405 Entries.push_back(PathEntry::ArrayIndex(0));
406
407 MostDerivedType = ElemTy;
408 MostDerivedIsArrayElement = true;
409 // The value in MostDerivedArraySize is undefined in this case. So, set it
410 // to an arbitrary value that's likely to loudly break things if it's
411 // used.
412 MostDerivedArraySize = AssumedSizeForUnsizedArray;
413 MostDerivedPathLength = Entries.size();
414 }
415 /// Update this designator to refer to the given base or member of this
416 /// object.
417 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
418 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
419
420 // If this isn't a base class, it's a new most-derived object.
421 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
422 MostDerivedType = FD->getType();
423 MostDerivedIsArrayElement = false;
424 MostDerivedArraySize = 0;
425 MostDerivedPathLength = Entries.size();
426 }
427 }
428 /// Update this designator to refer to the given complex component.
429 void addComplexUnchecked(QualType EltTy, bool Imag) {
430 Entries.push_back(PathEntry::ArrayIndex(Imag));
431
432 // This is technically a most-derived object, though in practice this
433 // is unlikely to matter.
434 MostDerivedType = EltTy;
435 MostDerivedIsArrayElement = true;
436 MostDerivedArraySize = 2;
437 MostDerivedPathLength = Entries.size();
438 }
439 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
440 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
441 const APSInt &N);
442 /// Add N to the address of this subobject.
443 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
444 if (Invalid || !N) return;
445 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
446 if (isMostDerivedAnUnsizedArray()) {
447 diagnoseUnsizedArrayPointerArithmetic(Info, E);
448 // Can't verify -- trust that the user is doing the right thing (or if
449 // not, trust that the caller will catch the bad behavior).
450 // FIXME: Should we reject if this overflows, at least?
451 Entries.back() = PathEntry::ArrayIndex(
452 Entries.back().getAsArrayIndex() + TruncatedN);
453 return;
454 }
455
456 // [expr.add]p4: For the purposes of these operators, a pointer to a
457 // nonarray object behaves the same as a pointer to the first element of
458 // an array of length one with the type of the object as its element type.
459 bool IsArray = MostDerivedPathLength == Entries.size() &&
460 MostDerivedIsArrayElement;
461 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
462 : (uint64_t)IsOnePastTheEnd;
463 uint64_t ArraySize =
464 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
465
466 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
467 // Calculate the actual index in a wide enough type, so we can include
468 // it in the note.
469 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
470 (llvm::APInt&)N += ArrayIndex;
471 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", 471, __extension__ __PRETTY_FUNCTION__
))
;
472 diagnosePointerArithmetic(Info, E, N);
473 setInvalid();
474 return;
475 }
476
477 ArrayIndex += TruncatedN;
478 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", 479, __extension__ __PRETTY_FUNCTION__
))
479 "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", 479, __extension__ __PRETTY_FUNCTION__
))
;
480
481 if (IsArray)
482 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
483 else
484 IsOnePastTheEnd = (ArrayIndex != 0);
485 }
486 };
487
488 /// A scope at the end of which an object can need to be destroyed.
489 enum class ScopeKind {
490 Block,
491 FullExpression,
492 Call
493 };
494
495 /// A reference to a particular call and its arguments.
496 struct CallRef {
497 CallRef() : OrigCallee(), CallIndex(0), Version() {}
498 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
499 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
500
501 explicit operator bool() const { return OrigCallee; }
502
503 /// Get the parameter that the caller initialized, corresponding to the
504 /// given parameter in the callee.
505 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
506 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
507 : PVD;
508 }
509
510 /// The callee at the point where the arguments were evaluated. This might
511 /// be different from the actual callee (a different redeclaration, or a
512 /// virtual override), but this function's parameters are the ones that
513 /// appear in the parameter map.
514 const FunctionDecl *OrigCallee;
515 /// The call index of the frame that holds the argument values.
516 unsigned CallIndex;
517 /// The version of the parameters corresponding to this call.
518 unsigned Version;
519 };
520
521 /// A stack frame in the constexpr call stack.
522 class CallStackFrame : public interp::Frame {
523 public:
524 EvalInfo &Info;
525
526 /// Parent - The caller of this stack frame.
527 CallStackFrame *Caller;
528
529 /// Callee - The function which was called.
530 const FunctionDecl *Callee;
531
532 /// This - The binding for the this pointer in this call, if any.
533 const LValue *This;
534
535 /// Information on how to find the arguments to this call. Our arguments
536 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
537 /// key and this value as the version.
538 CallRef Arguments;
539
540 /// Source location information about the default argument or default
541 /// initializer expression we're evaluating, if any.
542 CurrentSourceLocExprScope CurSourceLocExprScope;
543
544 // Note that we intentionally use std::map here so that references to
545 // values are stable.
546 typedef std::pair<const void *, unsigned> MapKeyTy;
547 typedef std::map<MapKeyTy, APValue> MapTy;
548 /// Temporaries - Temporary lvalues materialized within this stack frame.
549 MapTy Temporaries;
550
551 /// CallLoc - The location of the call expression for this call.
552 SourceLocation CallLoc;
553
554 /// Index - The call index of this call.
555 unsigned Index;
556
557 /// The stack of integers for tracking version numbers for temporaries.
558 SmallVector<unsigned, 2> TempVersionStack = {1};
559 unsigned CurTempVersion = TempVersionStack.back();
560
561 unsigned getTempVersion() const { return TempVersionStack.back(); }
562
563 void pushTempVersion() {
564 TempVersionStack.push_back(++CurTempVersion);
565 }
566
567 void popTempVersion() {
568 TempVersionStack.pop_back();
569 }
570
571 CallRef createCall(const FunctionDecl *Callee) {
572 return {Callee, Index, ++CurTempVersion};
573 }
574
575 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
576 // on the overall stack usage of deeply-recursing constexpr evaluations.
577 // (We should cache this map rather than recomputing it repeatedly.)
578 // But let's try this and see how it goes; we can look into caching the map
579 // as a later change.
580
581 /// LambdaCaptureFields - Mapping from captured variables/this to
582 /// corresponding data members in the closure class.
583 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
584 FieldDecl *LambdaThisCaptureField;
585
586 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
587 const FunctionDecl *Callee, const LValue *This,
588 CallRef Arguments);
589 ~CallStackFrame();
590
591 // Return the temporary for Key whose version number is Version.
592 APValue *getTemporary(const void *Key, unsigned Version) {
593 MapKeyTy KV(Key, Version);
594 auto LB = Temporaries.lower_bound(KV);
595 if (LB != Temporaries.end() && LB->first == KV)
596 return &LB->second;
597 return nullptr;
598 }
599
600 // Return the current temporary for Key in the map.
601 APValue *getCurrentTemporary(const void *Key) {
602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
604 return &std::prev(UB)->second;
605 return nullptr;
606 }
607
608 // Return the version number of the current temporary for Key.
609 unsigned getCurrentTemporaryVersion(const void *Key) const {
610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612 return std::prev(UB)->first.second;
613 return 0;
614 }
615
616 /// Allocate storage for an object of type T in this stack frame.
617 /// Populates LV with a handle to the created object. Key identifies
618 /// the temporary within the stack frame, and must not be reused without
619 /// bumping the temporary version number.
620 template<typename KeyT>
621 APValue &createTemporary(const KeyT *Key, QualType T,
622 ScopeKind Scope, LValue &LV);
623
624 /// Allocate storage for a parameter of a function call made in this frame.
625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
626
627 void describe(llvm::raw_ostream &OS) override;
628
629 Frame *getCaller() const override { return Caller; }
630 SourceLocation getCallLocation() const override { return CallLoc; }
631 const FunctionDecl *getCallee() const override { return Callee; }
632
633 bool isStdFunction() const {
634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
635 if (DC->isStdNamespace())
636 return true;
637 return false;
638 }
639
640 private:
641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
642 ScopeKind Scope);
643 };
644
645 /// Temporarily override 'this'.
646 class ThisOverrideRAII {
647 public:
648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
649 : Frame(Frame), OldThis(Frame.This) {
650 if (Enable)
651 Frame.This = NewThis;
652 }
653 ~ThisOverrideRAII() {
654 Frame.This = OldThis;
655 }
656 private:
657 CallStackFrame &Frame;
658 const LValue *OldThis;
659 };
660
661 // A shorthand time trace scope struct, prints source range, for example
662 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
663 class ExprTimeTraceScope {
664 public:
665 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
666 : TimeScope(Name, [E, &Ctx] {
667 return E->getSourceRange().printToString(Ctx.getSourceManager());
668 }) {}
669
670 private:
671 llvm::TimeTraceScope TimeScope;
672 };
673}
674
675static bool HandleDestruction(EvalInfo &Info, const Expr *E,
676 const LValue &This, QualType ThisType);
677static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
678 APValue::LValueBase LVBase, APValue &Value,
679 QualType T);
680
681namespace {
682 /// A cleanup, and a flag indicating whether it is lifetime-extended.
683 class Cleanup {
684 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
685 APValue::LValueBase Base;
686 QualType T;
687
688 public:
689 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
690 ScopeKind Scope)
691 : Value(Val, Scope), Base(Base), T(T) {}
692
693 /// Determine whether this cleanup should be performed at the end of the
694 /// given kind of scope.
695 bool isDestroyedAtEndOf(ScopeKind K) const {
696 return (int)Value.getInt() >= (int)K;
697 }
698 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
699 if (RunDestructors) {
700 SourceLocation Loc;
701 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
702 Loc = VD->getLocation();
703 else if (const Expr *E = Base.dyn_cast<const Expr*>())
704 Loc = E->getExprLoc();
705 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
706 }
707 *Value.getPointer() = APValue();
708 return true;
709 }
710
711 bool hasSideEffect() {
712 return T.isDestructedType();
713 }
714 };
715
716 /// A reference to an object whose construction we are currently evaluating.
717 struct ObjectUnderConstruction {
718 APValue::LValueBase Base;
719 ArrayRef<APValue::LValuePathEntry> Path;
720 friend bool operator==(const ObjectUnderConstruction &LHS,
721 const ObjectUnderConstruction &RHS) {
722 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
723 }
724 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
725 return llvm::hash_combine(Obj.Base, Obj.Path);
726 }
727 };
728 enum class ConstructionPhase {
729 None,
730 Bases,
731 AfterBases,
732 AfterFields,
733 Destroying,
734 DestroyingBases
735 };
736}
737
738namespace llvm {
739template<> struct DenseMapInfo<ObjectUnderConstruction> {
740 using Base = DenseMapInfo<APValue::LValueBase>;
741 static ObjectUnderConstruction getEmptyKey() {
742 return {Base::getEmptyKey(), {}}; }
743 static ObjectUnderConstruction getTombstoneKey() {
744 return {Base::getTombstoneKey(), {}};
745 }
746 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
747 return hash_value(Object);
748 }
749 static bool isEqual(const ObjectUnderConstruction &LHS,
750 const ObjectUnderConstruction &RHS) {
751 return LHS == RHS;
752 }
753};
754}
755
756namespace {
757 /// A dynamically-allocated heap object.
758 struct DynAlloc {
759 /// The value of this heap-allocated object.
760 APValue Value;
761 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
762 /// or a CallExpr (the latter is for direct calls to operator new inside
763 /// std::allocator<T>::allocate).
764 const Expr *AllocExpr = nullptr;
765
766 enum Kind {
767 New,
768 ArrayNew,
769 StdAllocator
770 };
771
772 /// Get the kind of the allocation. This must match between allocation
773 /// and deallocation.
774 Kind getKind() const {
775 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
776 return NE->isArray() ? ArrayNew : New;
777 assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void
(0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "clang/lib/AST/ExprConstant.cpp"
, 777, __extension__ __PRETTY_FUNCTION__))
;
778 return StdAllocator;
779 }
780 };
781
782 struct DynAllocOrder {
783 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
784 return L.getIndex() < R.getIndex();
785 }
786 };
787
788 /// EvalInfo - This is a private struct used by the evaluator to capture
789 /// information about a subexpression as it is folded. It retains information
790 /// about the AST context, but also maintains information about the folded
791 /// expression.
792 ///
793 /// If an expression could be evaluated, it is still possible it is not a C
794 /// "integer constant expression" or constant expression. If not, this struct
795 /// captures information about how and why not.
796 ///
797 /// One bit of information passed *into* the request for constant folding
798 /// indicates whether the subexpression is "evaluated" or not according to C
799 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
800 /// evaluate the expression regardless of what the RHS is, but C only allows
801 /// certain things in certain situations.
802 class EvalInfo : public interp::State {
803 public:
804 ASTContext &Ctx;
805
806 /// EvalStatus - Contains information about the evaluation.
807 Expr::EvalStatus &EvalStatus;
808
809 /// CurrentCall - The top of the constexpr call stack.
810 CallStackFrame *CurrentCall;
811
812 /// CallStackDepth - The number of calls in the call stack right now.
813 unsigned CallStackDepth;
814
815 /// NextCallIndex - The next call index to assign.
816 unsigned NextCallIndex;
817
818 /// StepsLeft - The remaining number of evaluation steps we're permitted
819 /// to perform. This is essentially a limit for the number of statements
820 /// we will evaluate.
821 unsigned StepsLeft;
822
823 /// Enable the experimental new constant interpreter. If an expression is
824 /// not supported by the interpreter, an error is triggered.
825 bool EnableNewConstInterp;
826
827 /// BottomFrame - The frame in which evaluation started. This must be
828 /// initialized after CurrentCall and CallStackDepth.
829 CallStackFrame BottomFrame;
830
831 /// A stack of values whose lifetimes end at the end of some surrounding
832 /// evaluation frame.
833 llvm::SmallVector<Cleanup, 16> CleanupStack;
834
835 /// EvaluatingDecl - This is the declaration whose initializer is being
836 /// evaluated, if any.
837 APValue::LValueBase EvaluatingDecl;
838
839 enum class EvaluatingDeclKind {
840 None,
841 /// We're evaluating the construction of EvaluatingDecl.
842 Ctor,
843 /// We're evaluating the destruction of EvaluatingDecl.
844 Dtor,
845 };
846 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
847
848 /// EvaluatingDeclValue - This is the value being constructed for the
849 /// declaration whose initializer is being evaluated, if any.
850 APValue *EvaluatingDeclValue;
851
852 /// Set of objects that are currently being constructed.
853 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
854 ObjectsUnderConstruction;
855
856 /// Current heap allocations, along with the location where each was
857 /// allocated. We use std::map here because we need stable addresses
858 /// for the stored APValues.
859 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
860
861 /// The number of heap allocations performed so far in this evaluation.
862 unsigned NumHeapAllocs = 0;
863
864 struct EvaluatingConstructorRAII {
865 EvalInfo &EI;
866 ObjectUnderConstruction Object;
867 bool DidInsert;
868 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
869 bool HasBases)
870 : EI(EI), Object(Object) {
871 DidInsert =
872 EI.ObjectsUnderConstruction
873 .insert({Object, HasBases ? ConstructionPhase::Bases
874 : ConstructionPhase::AfterBases})
875 .second;
876 }
877 void finishedConstructingBases() {
878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
879 }
880 void finishedConstructingFields() {
881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
882 }
883 ~EvaluatingConstructorRAII() {
884 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
885 }
886 };
887
888 struct EvaluatingDestructorRAII {
889 EvalInfo &EI;
890 ObjectUnderConstruction Object;
891 bool DidInsert;
892 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
893 : EI(EI), Object(Object) {
894 DidInsert = EI.ObjectsUnderConstruction
895 .insert({Object, ConstructionPhase::Destroying})
896 .second;
897 }
898 void startedDestroyingBases() {
899 EI.ObjectsUnderConstruction[Object] =
900 ConstructionPhase::DestroyingBases;
901 }
902 ~EvaluatingDestructorRAII() {
903 if (DidInsert)
904 EI.ObjectsUnderConstruction.erase(Object);
905 }
906 };
907
908 ConstructionPhase
909 isEvaluatingCtorDtor(APValue::LValueBase Base,
910 ArrayRef<APValue::LValuePathEntry> Path) {
911 return ObjectsUnderConstruction.lookup({Base, Path});
912 }
913
914 /// If we're currently speculatively evaluating, the outermost call stack
915 /// depth at which we can mutate state, otherwise 0.
916 unsigned SpeculativeEvaluationDepth = 0;
917
918 /// The current array initialization index, if we're performing array
919 /// initialization.
920 uint64_t ArrayInitIndex = -1;
921
922 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
923 /// notes attached to it will also be stored, otherwise they will not be.
924 bool HasActiveDiagnostic;
925
926 /// Have we emitted a diagnostic explaining why we couldn't constant
927 /// fold (not just why it's not strictly a constant expression)?
928 bool HasFoldFailureDiagnostic;
929
930 /// Whether or not we're in a context where the front end requires a
931 /// constant value.
932 bool InConstantContext;
933
934 /// Whether we're checking that an expression is a potential constant
935 /// expression. If so, do not fail on constructs that could become constant
936 /// later on (such as a use of an undefined global).
937 bool CheckingPotentialConstantExpression = false;
938
939 /// Whether we're checking for an expression that has undefined behavior.
940 /// If so, we will produce warnings if we encounter an operation that is
941 /// always undefined.
942 ///
943 /// Note that we still need to evaluate the expression normally when this
944 /// is set; this is used when evaluating ICEs in C.
945 bool CheckingForUndefinedBehavior = false;
946
947 enum EvaluationMode {
948 /// Evaluate as a constant expression. Stop if we find that the expression
949 /// is not a constant expression.
950 EM_ConstantExpression,
951
952 /// Evaluate as a constant expression. Stop if we find that the expression
953 /// is not a constant expression. Some expressions can be retried in the
954 /// optimizer if we don't constant fold them here, but in an unevaluated
955 /// context we try to fold them immediately since the optimizer never
956 /// gets a chance to look at it.
957 EM_ConstantExpressionUnevaluated,
958
959 /// Fold the expression to a constant. Stop if we hit a side-effect that
960 /// we can't model.
961 EM_ConstantFold,
962
963 /// Evaluate in any way we know how. Don't worry about side-effects that
964 /// can't be modeled.
965 EM_IgnoreSideEffects,
966 } EvalMode;
967
968 /// Are we checking whether the expression is a potential constant
969 /// expression?
970 bool checkingPotentialConstantExpression() const override {
971 return CheckingPotentialConstantExpression;
972 }
973
974 /// Are we checking an expression for overflow?
975 // FIXME: We should check for any kind of undefined or suspicious behavior
976 // in such constructs, not just overflow.
977 bool checkingForUndefinedBehavior() const override {
978 return CheckingForUndefinedBehavior;
979 }
980
981 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
982 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
983 CallStackDepth(0), NextCallIndex(1),
984 StepsLeft(C.getLangOpts().ConstexprStepLimit),
985 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
986 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
987 EvaluatingDecl((const ValueDecl *)nullptr),
988 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
989 HasFoldFailureDiagnostic(false), InConstantContext(false),
990 EvalMode(Mode) {}
991
992 ~EvalInfo() {
993 discardCleanups();
994 }
995
996 ASTContext &getCtx() const override { return Ctx; }
997
998 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
999 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1000 EvaluatingDecl = Base;
1001 IsEvaluatingDecl = EDK;
1002 EvaluatingDeclValue = &Value;
1003 }
1004
1005 bool CheckCallLimit(SourceLocation Loc) {
1006 // Don't perform any constexpr calls (other than the call we're checking)
1007 // when checking a potential constant expression.
1008 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1009 return false;
1010 if (NextCallIndex == 0) {
1011 // NextCallIndex has wrapped around.
1012 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1013 return false;
1014 }
1015 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1016 return true;
1017 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1018 << getLangOpts().ConstexprCallDepth;
1019 return false;
1020 }
1021
1022 std::pair<CallStackFrame *, unsigned>
1023 getCallFrameAndDepth(unsigned CallIndex) {
1024 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", 1024, __extension__ __PRETTY_FUNCTION__
))
;
1025 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1026 // be null in this loop.
1027 unsigned Depth = CallStackDepth;
1028 CallStackFrame *Frame = CurrentCall;
1029 while (Frame->Index > CallIndex) {
1030 Frame = Frame->Caller;
1031 --Depth;
1032 }
1033 if (Frame->Index == CallIndex)
1034 return {Frame, Depth};
1035 return {nullptr, 0};
1036 }
1037
1038 bool nextStep(const Stmt *S) {
1039 if (!StepsLeft) {
1040 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1041 return false;
1042 }
1043 --StepsLeft;
1044 return true;
1045 }
1046
1047 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1048
1049 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1050 Optional<DynAlloc*> Result;
1051 auto It = HeapAllocs.find(DA);
1052 if (It != HeapAllocs.end())
1053 Result = &It->second;
1054 return Result;
1055 }
1056
1057 /// Get the allocated storage for the given parameter of the given call.
1058 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1059 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1060 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1061 : nullptr;
1062 }
1063
1064 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1065 struct StdAllocatorCaller {
1066 unsigned FrameIndex;
1067 QualType ElemType;
1068 explicit operator bool() const { return FrameIndex != 0; };
1069 };
1070
1071 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1072 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1073 Call = Call->Caller) {
1074 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1075 if (!MD)
1076 continue;
1077 const IdentifierInfo *FnII = MD->getIdentifier();
1078 if (!FnII || !FnII->isStr(FnName))
1079 continue;
1080
1081 const auto *CTSD =
1082 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1083 if (!CTSD)
1084 continue;
1085
1086 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1087 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1088 if (CTSD->isInStdNamespace() && ClassII &&
1089 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1090 TAL[0].getKind() == TemplateArgument::Type)
1091 return {Call->Index, TAL[0].getAsType()};
1092 }
1093
1094 return {};
1095 }
1096
1097 void performLifetimeExtension() {
1098 // Disable the cleanups for lifetime-extended temporaries.
1099 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1100 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1101 });
1102 }
1103
1104 /// Throw away any remaining cleanups at the end of evaluation. If any
1105 /// cleanups would have had a side-effect, note that as an unmodeled
1106 /// side-effect and return false. Otherwise, return true.
1107 bool discardCleanups() {
1108 for (Cleanup &C : CleanupStack) {
1109 if (C.hasSideEffect() && !noteSideEffect()) {
1110 CleanupStack.clear();
1111 return false;
1112 }
1113 }
1114 CleanupStack.clear();
1115 return true;
1116 }
1117
1118 private:
1119 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1120 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1121
1122 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1123 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1124
1125 void setFoldFailureDiagnostic(bool Flag) override {
1126 HasFoldFailureDiagnostic = Flag;
1127 }
1128
1129 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1130
1131 // If we have a prior diagnostic, it will be noting that the expression
1132 // isn't a constant expression. This diagnostic is more important,
1133 // unless we require this evaluation to produce a constant expression.
1134 //
1135 // FIXME: We might want to show both diagnostics to the user in
1136 // EM_ConstantFold mode.
1137 bool hasPriorDiagnostic() override {
1138 if (!EvalStatus.Diag->empty()) {
1139 switch (EvalMode) {
1140 case EM_ConstantFold:
1141 case EM_IgnoreSideEffects:
1142 if (!HasFoldFailureDiagnostic)
1143 break;
1144 // We've already failed to fold something. Keep that diagnostic.
1145 [[fallthrough]];
1146 case EM_ConstantExpression:
1147 case EM_ConstantExpressionUnevaluated:
1148 setActiveDiagnostic(false);
1149 return true;
1150 }
1151 }
1152 return false;
1153 }
1154
1155 unsigned getCallStackDepth() override { return CallStackDepth; }
1156
1157 public:
1158 /// Should we continue evaluation after encountering a side-effect that we
1159 /// couldn't model?
1160 bool keepEvaluatingAfterSideEffect() {
1161 switch (EvalMode) {
1162 case EM_IgnoreSideEffects:
1163 return true;
1164
1165 case EM_ConstantExpression:
1166 case EM_ConstantExpressionUnevaluated:
1167 case EM_ConstantFold:
1168 // By default, assume any side effect might be valid in some other
1169 // evaluation of this expression from a different context.
1170 return checkingPotentialConstantExpression() ||
1171 checkingForUndefinedBehavior();
1172 }
1173 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1173)
;
1174 }
1175
1176 /// Note that we have had a side-effect, and determine whether we should
1177 /// keep evaluating.
1178 bool noteSideEffect() {
1179 EvalStatus.HasSideEffects = true;
1180 return keepEvaluatingAfterSideEffect();
1181 }
1182
1183 /// Should we continue evaluation after encountering undefined behavior?
1184 bool keepEvaluatingAfterUndefinedBehavior() {
1185 switch (EvalMode) {
1186 case EM_IgnoreSideEffects:
1187 case EM_ConstantFold:
1188 return true;
1189
1190 case EM_ConstantExpression:
1191 case EM_ConstantExpressionUnevaluated:
1192 return checkingForUndefinedBehavior();
1193 }
1194 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1194)
;
1195 }
1196
1197 /// Note that we hit something that was technically undefined behavior, but
1198 /// that we can evaluate past it (such as signed overflow or floating-point
1199 /// division by zero.)
1200 bool noteUndefinedBehavior() override {
1201 EvalStatus.HasUndefinedBehavior = true;
1202 return keepEvaluatingAfterUndefinedBehavior();
1203 }
1204
1205 /// Should we continue evaluation as much as possible after encountering a
1206 /// construct which can't be reduced to a value?
1207 bool keepEvaluatingAfterFailure() const override {
1208 if (!StepsLeft)
1209 return false;
1210
1211 switch (EvalMode) {
1212 case EM_ConstantExpression:
1213 case EM_ConstantExpressionUnevaluated:
1214 case EM_ConstantFold:
1215 case EM_IgnoreSideEffects:
1216 return checkingPotentialConstantExpression() ||
1217 checkingForUndefinedBehavior();
1218 }
1219 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1219)
;
1220 }
1221
1222 /// Notes that we failed to evaluate an expression that other expressions
1223 /// directly depend on, and determine if we should keep evaluating. This
1224 /// should only be called if we actually intend to keep evaluating.
1225 ///
1226 /// Call noteSideEffect() instead if we may be able to ignore the value that
1227 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1228 ///
1229 /// (Foo(), 1) // use noteSideEffect
1230 /// (Foo() || true) // use noteSideEffect
1231 /// Foo() + 1 // use noteFailure
1232 [[nodiscard]] bool noteFailure() {
1233 // Failure when evaluating some expression often means there is some
1234 // subexpression whose evaluation was skipped. Therefore, (because we
1235 // don't track whether we skipped an expression when unwinding after an
1236 // evaluation failure) every evaluation failure that bubbles up from a
1237 // subexpression implies that a side-effect has potentially happened. We
1238 // skip setting the HasSideEffects flag to true until we decide to
1239 // continue evaluating after that point, which happens here.
1240 bool KeepGoing = keepEvaluatingAfterFailure();
1241 EvalStatus.HasSideEffects |= KeepGoing;
1242 return KeepGoing;
1243 }
1244
1245 class ArrayInitLoopIndex {
1246 EvalInfo &Info;
1247 uint64_t OuterIndex;
1248
1249 public:
1250 ArrayInitLoopIndex(EvalInfo &Info)
1251 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1252 Info.ArrayInitIndex = 0;
1253 }
1254 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1255
1256 operator uint64_t&() { return Info.ArrayInitIndex; }
1257 };
1258 };
1259
1260 /// Object used to treat all foldable expressions as constant expressions.
1261 struct FoldConstant {
1262 EvalInfo &Info;
1263 bool Enabled;
1264 bool HadNoPriorDiags;
1265 EvalInfo::EvaluationMode OldMode;
1266
1267 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1268 : Info(Info),
1269 Enabled(Enabled),
1270 HadNoPriorDiags(Info.EvalStatus.Diag &&
1271 Info.EvalStatus.Diag->empty() &&
1272 !Info.EvalStatus.HasSideEffects),
1273 OldMode(Info.EvalMode) {
1274 if (Enabled)
1275 Info.EvalMode = EvalInfo::EM_ConstantFold;
1276 }
1277 void keepDiagnostics() { Enabled = false; }
1278 ~FoldConstant() {
1279 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1280 !Info.EvalStatus.HasSideEffects)
1281 Info.EvalStatus.Diag->clear();
1282 Info.EvalMode = OldMode;
1283 }
1284 };
1285
1286 /// RAII object used to set the current evaluation mode to ignore
1287 /// side-effects.
1288 struct IgnoreSideEffectsRAII {
1289 EvalInfo &Info;
1290 EvalInfo::EvaluationMode OldMode;
1291 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1292 : Info(Info), OldMode(Info.EvalMode) {
1293 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1294 }
1295
1296 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1297 };
1298
1299 /// RAII object used to optionally suppress diagnostics and side-effects from
1300 /// a speculative evaluation.
1301 class SpeculativeEvaluationRAII {
1302 EvalInfo *Info = nullptr;
1303 Expr::EvalStatus OldStatus;
1304 unsigned OldSpeculativeEvaluationDepth;
1305
1306 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1307 Info = Other.Info;
1308 OldStatus = Other.OldStatus;
1309 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1310 Other.Info = nullptr;
1311 }
1312
1313 void maybeRestoreState() {
1314 if (!Info)
1315 return;
1316
1317 Info->EvalStatus = OldStatus;
1318 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1319 }
1320
1321 public:
1322 SpeculativeEvaluationRAII() = default;
1323
1324 SpeculativeEvaluationRAII(
1325 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1326 : Info(&Info), OldStatus(Info.EvalStatus),
1327 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1328 Info.EvalStatus.Diag = NewDiag;
1329 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1330 }
1331
1332 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1333 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1334 moveFromAndCancel(std::move(Other));
1335 }
1336
1337 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1338 maybeRestoreState();
1339 moveFromAndCancel(std::move(Other));
1340 return *this;
1341 }
1342
1343 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1344 };
1345
1346 /// RAII object wrapping a full-expression or block scope, and handling
1347 /// the ending of the lifetime of temporaries created within it.
1348 template<ScopeKind Kind>
1349 class ScopeRAII {
1350 EvalInfo &Info;
1351 unsigned OldStackSize;
1352 public:
1353 ScopeRAII(EvalInfo &Info)
1354 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1355 // Push a new temporary version. This is needed to distinguish between
1356 // temporaries created in different iterations of a loop.
1357 Info.CurrentCall->pushTempVersion();
1358 }
1359 bool destroy(bool RunDestructors = true) {
1360 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1361 OldStackSize = -1U;
1362 return OK;
1363 }
1364 ~ScopeRAII() {
1365 if (OldStackSize != -1U)
1366 destroy(false);
1367 // Body moved to a static method to encourage the compiler to inline away
1368 // instances of this class.
1369 Info.CurrentCall->popTempVersion();
1370 }
1371 private:
1372 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1373 unsigned OldStackSize) {
1374 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", 1375, __extension__ __PRETTY_FUNCTION__
))
1375 "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", 1375, __extension__ __PRETTY_FUNCTION__
))
;
1376
1377 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1378 // for a full-expression scope.
1379 bool Success = true;
1380 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1381 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1382 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1383 Success = false;
1384 break;
1385 }
1386 }
1387 }
1388
1389 // Compact any retained cleanups.
1390 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1391 if (Kind != ScopeKind::Block)
1392 NewEnd =
1393 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1394 return C.isDestroyedAtEndOf(Kind);
1395 });
1396 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1397 return Success;
1398 }
1399 };
1400 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1401 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1402 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1403}
1404
1405bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1406 CheckSubobjectKind CSK) {
1407 if (Invalid)
1408 return false;
1409 if (isOnePastTheEnd()) {
1410 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1411 << CSK;
1412 setInvalid();
1413 return false;
1414 }
1415 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1416 // must actually be at least one array element; even a VLA cannot have a
1417 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1418 return true;
1419}
1420
1421void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1422 const Expr *E) {
1423 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1424 // Do not set the designator as invalid: we can represent this situation,
1425 // and correct handling of __builtin_object_size requires us to do so.
1426}
1427
1428void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1429 const Expr *E,
1430 const APSInt &N) {
1431 // If we're complaining, we must be able to statically determine the size of
1432 // the most derived array.
1433 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1434 Info.CCEDiag(E, diag::note_constexpr_array_index)
1435 << N << /*array*/ 0
1436 << static_cast<unsigned>(getMostDerivedArraySize());
1437 else
1438 Info.CCEDiag(E, diag::note_constexpr_array_index)
1439 << N << /*non-array*/ 1;
1440 setInvalid();
1441}
1442
1443CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1444 const FunctionDecl *Callee, const LValue *This,
1445 CallRef Call)
1446 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1447 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1448 Info.CurrentCall = this;
1449 ++Info.CallStackDepth;
1450}
1451
1452CallStackFrame::~CallStackFrame() {
1453 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", 1453, __extension__ __PRETTY_FUNCTION__
))
;
1454 --Info.CallStackDepth;
1455 Info.CurrentCall = Caller;
1456}
1457
1458static bool isRead(AccessKinds AK) {
1459 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1460}
1461
1462static bool isModification(AccessKinds AK) {
1463 switch (AK) {
1464 case AK_Read:
1465 case AK_ReadObjectRepresentation:
1466 case AK_MemberCall:
1467 case AK_DynamicCast:
1468 case AK_TypeId:
1469 return false;
1470 case AK_Assign:
1471 case AK_Increment:
1472 case AK_Decrement:
1473 case AK_Construct:
1474 case AK_Destroy:
1475 return true;
1476 }
1477 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1477)
;
1478}
1479
1480static bool isAnyAccess(AccessKinds AK) {
1481 return isRead(AK) || isModification(AK);
1482}
1483
1484/// Is this an access per the C++ definition?
1485static bool isFormalAccess(AccessKinds AK) {
1486 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1487}
1488
1489/// Is this kind of axcess valid on an indeterminate object value?
1490static bool isValidIndeterminateAccess(AccessKinds AK) {
1491 switch (AK) {
1492 case AK_Read:
1493 case AK_Increment:
1494 case AK_Decrement:
1495 // These need the object's value.
1496 return false;
1497
1498 case AK_ReadObjectRepresentation:
1499 case AK_Assign:
1500 case AK_Construct:
1501 case AK_Destroy:
1502 // Construction and destruction don't need the value.
1503 return true;
1504
1505 case AK_MemberCall:
1506 case AK_DynamicCast:
1507 case AK_TypeId:
1508 // These aren't really meaningful on scalars.
1509 return true;
1510 }
1511 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1511)
;
1512}
1513
1514namespace {
1515 struct ComplexValue {
1516 private:
1517 bool IsInt;
1518
1519 public:
1520 APSInt IntReal, IntImag;
1521 APFloat FloatReal, FloatImag;
1522
1523 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1524
1525 void makeComplexFloat() { IsInt = false; }
1526 bool isComplexFloat() const { return !IsInt; }
1527 APFloat &getComplexFloatReal() { return FloatReal; }
1528 APFloat &getComplexFloatImag() { return FloatImag; }
1529
1530 void makeComplexInt() { IsInt = true; }
1531 bool isComplexInt() const { return IsInt; }
1532 APSInt &getComplexIntReal() { return IntReal; }
1533 APSInt &getComplexIntImag() { return IntImag; }
1534
1535 void moveInto(APValue &v) const {
1536 if (isComplexFloat())
1537 v = APValue(FloatReal, FloatImag);
1538 else
1539 v = APValue(IntReal, IntImag);
1540 }
1541 void setFrom(const APValue &v) {
1542 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", 1542, __extension__ __PRETTY_FUNCTION__
))
;
1543 if (v.isComplexFloat()) {
1544 makeComplexFloat();
1545 FloatReal = v.getComplexFloatReal();
1546 FloatImag = v.getComplexFloatImag();
1547 } else {
1548 makeComplexInt();
1549 IntReal = v.getComplexIntReal();
1550 IntImag = v.getComplexIntImag();
1551 }
1552 }
1553 };
1554
1555 struct LValue {
1556 APValue::LValueBase Base;
1557 CharUnits Offset;
1558 SubobjectDesignator Designator;
1559 bool IsNullPtr : 1;
1560 bool InvalidBase : 1;
1561
1562 const APValue::LValueBase getLValueBase() const { return Base; }
1563 CharUnits &getLValueOffset() { return Offset; }
1564 const CharUnits &getLValueOffset() const { return Offset; }
1565 SubobjectDesignator &getLValueDesignator() { return Designator; }
1566 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1567 bool isNullPointer() const { return IsNullPtr;}
1568
1569 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1570 unsigned getLValueVersion() const { return Base.getVersion(); }
1571
1572 void moveInto(APValue &V) const {
1573 if (Designator.Invalid)
1574 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1575 else {
1576 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", 1576, __extension__ __PRETTY_FUNCTION__
))
;
1577 V = APValue(Base, Offset, Designator.Entries,
1578 Designator.IsOnePastTheEnd, IsNullPtr);
1579 }
1580 }
1581 void setFrom(ASTContext &Ctx, const APValue &V) {
1582 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", 1582, __extension__ __PRETTY_FUNCTION__
))
;
1583 Base = V.getLValueBase();
1584 Offset = V.getLValueOffset();
1585 InvalidBase = false;
1586 Designator = SubobjectDesignator(Ctx, V);
1587 IsNullPtr = V.isNullPointer();
1588 }
1589
1590 void set(APValue::LValueBase B, bool BInvalid = false) {
1591#ifndef NDEBUG
1592 // We only allow a few types of invalid bases. Enforce that here.
1593 if (BInvalid) {
1594 const auto *E = B.get<const Expr *>();
1595 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", 1596, __extension__ __PRETTY_FUNCTION__
))
1596 "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", 1596, __extension__ __PRETTY_FUNCTION__
))
;
1597 }
1598#endif
1599
1600 Base = B;
1601 Offset = CharUnits::fromQuantity(0);
1602 InvalidBase = BInvalid;
1603 Designator = SubobjectDesignator(getType(B));
1604 IsNullPtr = false;
1605 }
1606
1607 void setNull(ASTContext &Ctx, QualType PointerTy) {
1608 Base = (const ValueDecl *)nullptr;
1609 Offset =
1610 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1611 InvalidBase = false;
1612 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1613 IsNullPtr = true;
1614 }
1615
1616 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1617 set(B, true);
1618 }
1619
1620 std::string toString(ASTContext &Ctx, QualType T) const {
1621 APValue Printable;
1622 moveInto(Printable);
1623 return Printable.getAsString(Ctx, T);
1624 }
1625
1626 private:
1627 // Check that this LValue is not based on a null pointer. If it is, produce
1628 // a diagnostic and mark the designator as invalid.
1629 template <typename GenDiagType>
1630 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1631 if (Designator.Invalid)
1632 return false;
1633 if (IsNullPtr) {
1634 GenDiag();
1635 Designator.setInvalid();
1636 return false;
1637 }
1638 return true;
1639 }
1640
1641 public:
1642 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1643 CheckSubobjectKind CSK) {
1644 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1645 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1646 });
1647 }
1648
1649 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1650 AccessKinds AK) {
1651 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1652 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1653 });
1654 }
1655
1656 // Check this LValue refers to an object. If not, set the designator to be
1657 // invalid and emit a diagnostic.
1658 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1659 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1660 Designator.checkSubobject(Info, E, CSK);
1661 }
1662
1663 void addDecl(EvalInfo &Info, const Expr *E,
1664 const Decl *D, bool Virtual = false) {
1665 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1666 Designator.addDeclUnchecked(D, Virtual);
1667 }
1668 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1669 if (!Designator.Entries.empty()) {
1670 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1671 Designator.setInvalid();
1672 return;
1673 }
1674 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1675 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", 1675, __extension__ __PRETTY_FUNCTION__
))
;
1676 Designator.FirstEntryIsAnUnsizedArray = true;
1677 Designator.addUnsizedArrayUnchecked(ElemTy);
1678 }
1679 }
1680 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1681 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1682 Designator.addArrayUnchecked(CAT);
1683 }
1684 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1685 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1686 Designator.addComplexUnchecked(EltTy, Imag);
1687 }
1688 void clearIsNullPointer() {
1689 IsNullPtr = false;
1690 }
1691 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1692 const APSInt &Index, CharUnits ElementSize) {
1693 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1694 // but we're not required to diagnose it and it's valid in C++.)
1695 if (!Index)
1696 return;
1697
1698 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1699 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1700 // offsets.
1701 uint64_t Offset64 = Offset.getQuantity();
1702 uint64_t ElemSize64 = ElementSize.getQuantity();
1703 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1704 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1705
1706 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1707 Designator.adjustIndex(Info, E, Index);
1708 clearIsNullPointer();
1709 }
1710 void adjustOffset(CharUnits N) {
1711 Offset += N;
1712 if (N.getQuantity())
1713 clearIsNullPointer();
1714 }
1715 };
1716
1717 struct MemberPtr {
1718 MemberPtr() {}
1719 explicit MemberPtr(const ValueDecl *Decl)
1720 : DeclAndIsDerivedMember(Decl, false) {}
1721
1722 /// The member or (direct or indirect) field referred to by this member
1723 /// pointer, or 0 if this is a null member pointer.
1724 const ValueDecl *getDecl() const {
1725 return DeclAndIsDerivedMember.getPointer();
1726 }
1727 /// Is this actually a member of some type derived from the relevant class?
1728 bool isDerivedMember() const {
1729 return DeclAndIsDerivedMember.getInt();
1730 }
1731 /// Get the class which the declaration actually lives in.
1732 const CXXRecordDecl *getContainingRecord() const {
1733 return cast<CXXRecordDecl>(
1734 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1735 }
1736
1737 void moveInto(APValue &V) const {
1738 V = APValue(getDecl(), isDerivedMember(), Path);
1739 }
1740 void setFrom(const APValue &V) {
1741 assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail
("V.isMemberPointer()", "clang/lib/AST/ExprConstant.cpp", 1741
, __extension__ __PRETTY_FUNCTION__))
;
1742 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1743 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1744 Path.clear();
1745 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1746 Path.insert(Path.end(), P.begin(), P.end());
1747 }
1748
1749 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1750 /// whether the member is a member of some class derived from the class type
1751 /// of the member pointer.
1752 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1753 /// Path - The path of base/derived classes from the member declaration's
1754 /// class (exclusive) to the class type of the member pointer (inclusive).
1755 SmallVector<const CXXRecordDecl*, 4> Path;
1756
1757 /// Perform a cast towards the class of the Decl (either up or down the
1758 /// hierarchy).
1759 bool castBack(const CXXRecordDecl *Class) {
1760 assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail
("!Path.empty()", "clang/lib/AST/ExprConstant.cpp", 1760, __extension__
__PRETTY_FUNCTION__))
;
1761 const CXXRecordDecl *Expected;
1762 if (Path.size() >= 2)
1763 Expected = Path[Path.size() - 2];
1764 else
1765 Expected = getContainingRecord();
1766 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1767 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1768 // if B does not contain the original member and is not a base or
1769 // derived class of the class containing the original member, the result
1770 // of the cast is undefined.
1771 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1772 // (D::*). We consider that to be a language defect.
1773 return false;
1774 }
1775 Path.pop_back();
1776 return true;
1777 }
1778 /// Perform a base-to-derived member pointer cast.
1779 bool castToDerived(const CXXRecordDecl *Derived) {
1780 if (!getDecl())
1781 return true;
1782 if (!isDerivedMember()) {
1783 Path.push_back(Derived);
1784 return true;
1785 }
1786 if (!castBack(Derived))
1787 return false;
1788 if (Path.empty())
1789 DeclAndIsDerivedMember.setInt(false);
1790 return true;
1791 }
1792 /// Perform a derived-to-base member pointer cast.
1793 bool castToBase(const CXXRecordDecl *Base) {
1794 if (!getDecl())
1795 return true;
1796 if (Path.empty())
1797 DeclAndIsDerivedMember.setInt(true);
1798 if (isDerivedMember()) {
1799 Path.push_back(Base);
1800 return true;
1801 }
1802 return castBack(Base);
1803 }
1804 };
1805
1806 /// Compare two member pointers, which are assumed to be of the same type.
1807 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1808 if (!LHS.getDecl() || !RHS.getDecl())
1809 return !LHS.getDecl() && !RHS.getDecl();
1810 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1811 return false;
1812 return LHS.Path == RHS.Path;
1813 }
1814}
1815
1816static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1817static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1818 const LValue &This, const Expr *E,
1819 bool AllowNonLiteralTypes = false);
1820static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1821 bool InvalidBaseOK = false);
1822static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1823 bool InvalidBaseOK = false);
1824static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1825 EvalInfo &Info);
1826static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1827static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1828static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1829 EvalInfo &Info);
1830static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1831static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1832static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1833 EvalInfo &Info);
1834static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1835static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1836 EvalInfo &Info);
1837
1838/// Evaluate an integer or fixed point expression into an APResult.
1839static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1840 EvalInfo &Info);
1841
1842/// Evaluate only a fixed point expression into an APResult.
1843static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1844 EvalInfo &Info);
1845
1846//===----------------------------------------------------------------------===//
1847// Misc utilities
1848//===----------------------------------------------------------------------===//
1849
1850/// Negate an APSInt in place, converting it to a signed form if necessary, and
1851/// preserving its value (by extending by up to one bit as needed).
1852static void negateAsSigned(APSInt &Int) {
1853 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1854 Int = Int.extend(Int.getBitWidth() + 1);
1855 Int.setIsSigned(true);
1856 }
1857 Int = -Int;
1858}
1859
1860template<typename KeyT>
1861APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1862 ScopeKind Scope, LValue &LV) {
1863 unsigned Version = getTempVersion();
1864 APValue::LValueBase Base(Key, Index, Version);
1865 LV.set(Base);
1866 return createLocal(Base, Key, T, Scope);
1867}
1868
1869/// Allocate storage for a parameter of a function call made in this frame.
1870APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1871 LValue &LV) {
1872 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", 1872, __extension__ __PRETTY_FUNCTION__
))
;
1873 APValue::LValueBase Base(PVD, Index, Args.Version);
1874 LV.set(Base);
1875 // We always destroy parameters at the end of the call, even if we'd allow
1876 // them to live to the end of the full-expression at runtime, in order to
1877 // give portable results and match other compilers.
1878 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1879}
1880
1881APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1882 QualType T, ScopeKind Scope) {
1883 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", 1883, __extension__ __PRETTY_FUNCTION__
))
;
1884 unsigned Version = Base.getVersion();
1885 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1886 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", 1886, __extension__ __PRETTY_FUNCTION__
))
;
1887
1888 // If we're creating a local immediately in the operand of a speculative
1889 // evaluation, don't register a cleanup to be run outside the speculative
1890 // evaluation context, since we won't actually be able to initialize this
1891 // object.
1892 if (Index <= Info.SpeculativeEvaluationDepth) {
1893 if (T.isDestructedType())
1894 Info.noteSideEffect();
1895 } else {
1896 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1897 }
1898 return Result;
1899}
1900
1901APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1902 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1903 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1904 return nullptr;
1905 }
1906
1907 DynamicAllocLValue DA(NumHeapAllocs++);
1908 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1909 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1910 std::forward_as_tuple(DA), std::tuple<>());
1911 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", 1911, __extension__ __PRETTY_FUNCTION__
))
;
1912 Result.first->second.AllocExpr = E;
1913 return &Result.first->second.Value;
1914}
1915
1916/// Produce a string describing the given constexpr call.
1917void CallStackFrame::describe(raw_ostream &Out) {
1918 unsigned ArgIndex = 0;
1919 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1920 !isa<CXXConstructorDecl>(Callee) &&
1921 cast<CXXMethodDecl>(Callee)->isInstance();
1922
1923 if (!IsMemberCall)
1924 Out << *Callee << '(';
1925
1926 if (This && IsMemberCall) {
1927 APValue Val;
1928 This->moveInto(Val);
1929 Val.printPretty(Out, Info.Ctx,
1930 This->Designator.MostDerivedType);
1931 // FIXME: Add parens around Val if needed.
1932 Out << "->" << *Callee << '(';
1933 IsMemberCall = false;
1934 }
1935
1936 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1937 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1938 if (ArgIndex > (unsigned)IsMemberCall)
1939 Out << ", ";
1940
1941 const ParmVarDecl *Param = *I;
1942 APValue *V = Info.getParamSlot(Arguments, Param);
1943 if (V)
1944 V->printPretty(Out, Info.Ctx, Param->getType());
1945 else
1946 Out << "<...>";
1947
1948 if (ArgIndex == 0 && IsMemberCall)
1949 Out << "->" << *Callee << '(';
1950 }
1951
1952 Out << ')';
1953}
1954
1955/// Evaluate an expression to see if it had side-effects, and discard its
1956/// result.
1957/// \return \c true if the caller should keep evaluating.
1958static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1959 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 1959, __extension__ __PRETTY_FUNCTION__))
;
1960 APValue Scratch;
1961 if (!Evaluate(Scratch, Info, E))
1962 // We don't need the value, but we might have skipped a side effect here.
1963 return Info.noteSideEffect();
1964 return true;
1965}
1966
1967/// Should this call expression be treated as a no-op?
1968static bool IsNoOpCall(const CallExpr *E) {
1969 unsigned Builtin = E->getBuiltinCallee();
1970 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1971 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1972 Builtin == Builtin::BI__builtin_function_start);
1973}
1974
1975static bool IsGlobalLValue(APValue::LValueBase B) {
1976 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1977 // constant expression of pointer type that evaluates to...
1978
1979 // ... a null pointer value, or a prvalue core constant expression of type
1980 // std::nullptr_t.
1981 if (!B) return true;
1982
1983 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1984 // ... the address of an object with static storage duration,
1985 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1986 return VD->hasGlobalStorage();
1987 if (isa<TemplateParamObjectDecl>(D))
1988 return true;
1989 // ... the address of a function,
1990 // ... the address of a GUID [MS extension],
1991 // ... the address of an unnamed global constant
1992 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1993 }
1994
1995 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1996 return true;
1997
1998 const Expr *E = B.get<const Expr*>();
1999 switch (E->getStmtClass()) {
2000 default:
2001 return false;
2002 case Expr::CompoundLiteralExprClass: {
2003 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2004 return CLE->isFileScope() && CLE->isLValue();
2005 }
2006 case Expr::MaterializeTemporaryExprClass:
2007 // A materialized temporary might have been lifetime-extended to static
2008 // storage duration.
2009 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2010 // A string literal has static storage duration.
2011 case Expr::StringLiteralClass:
2012 case Expr::PredefinedExprClass:
2013 case Expr::ObjCStringLiteralClass:
2014 case Expr::ObjCEncodeExprClass:
2015 return true;
2016 case Expr::ObjCBoxedExprClass:
2017 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2018 case Expr::CallExprClass:
2019 return IsNoOpCall(cast<CallExpr>(E));
2020 // For GCC compatibility, &&label has static storage duration.
2021 case Expr::AddrLabelExprClass:
2022 return true;
2023 // A Block literal expression may be used as the initialization value for
2024 // Block variables at global or local static scope.
2025 case Expr::BlockExprClass:
2026 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2027 // The APValue generated from a __builtin_source_location will be emitted as a
2028 // literal.
2029 case Expr::SourceLocExprClass:
2030 return true;
2031 case Expr::ImplicitValueInitExprClass:
2032 // FIXME:
2033 // We can never form an lvalue with an implicit value initialization as its
2034 // base through expression evaluation, so these only appear in one case: the
2035 // implicit variable declaration we invent when checking whether a constexpr
2036 // constructor can produce a constant expression. We must assume that such
2037 // an expression might be a global lvalue.
2038 return true;
2039 }
2040}
2041
2042static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2043 return LVal.Base.dyn_cast<const ValueDecl*>();
2044}
2045
2046static bool IsLiteralLValue(const LValue &Value) {
2047 if (Value.getLValueCallIndex())
2048 return false;
2049 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2050 return E && !isa<MaterializeTemporaryExpr>(E);
2051}
2052
2053static bool IsWeakLValue(const LValue &Value) {
2054 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2055 return Decl && Decl->isWeak();
2056}
2057
2058static bool isZeroSized(const LValue &Value) {
2059 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2060 if (Decl && isa<VarDecl>(Decl)) {
2061 QualType Ty = Decl->getType();
2062 if (Ty->isArrayType())
2063 return Ty->isIncompleteType() ||
2064 Decl->getASTContext().getTypeSize(Ty) == 0;
2065 }
2066 return false;
2067}
2068
2069static bool HasSameBase(const LValue &A, const LValue &B) {
2070 if (!A.getLValueBase())
2071 return !B.getLValueBase();
2072 if (!B.getLValueBase())
2073 return false;
2074
2075 if (A.getLValueBase().getOpaqueValue() !=
2076 B.getLValueBase().getOpaqueValue())
2077 return false;
2078
2079 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2080 A.getLValueVersion() == B.getLValueVersion();
2081}
2082
2083static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2084 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", 2084, __extension__ __PRETTY_FUNCTION__
))
;
2085 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2086
2087 // For a parameter, find the corresponding call stack frame (if it still
2088 // exists), and point at the parameter of the function definition we actually
2089 // invoked.
2090 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2091 unsigned Idx = PVD->getFunctionScopeIndex();
2092 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2093 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2094 F->Arguments.Version == Base.getVersion() && F->Callee &&
2095 Idx < F->Callee->getNumParams()) {
2096 VD = F->Callee->getParamDecl(Idx);
2097 break;
2098 }
2099 }
2100 }
2101
2102 if (VD)
2103 Info.Note(VD->getLocation(), diag::note_declared_at);
2104 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2105 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2106 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2107 // FIXME: Produce a note for dangling pointers too.
2108 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2109 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2110 diag::note_constexpr_dynamic_alloc_here);
2111 }
2112 // We have no information to show for a typeid(T) object.
2113}
2114
2115enum class CheckEvaluationResultKind {
2116 ConstantExpression,
2117 FullyInitialized,
2118};
2119
2120/// Materialized temporaries that we've already checked to determine if they're
2121/// initializsed by a constant expression.
2122using CheckedTemporaries =
2123 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2124
2125static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2126 EvalInfo &Info, SourceLocation DiagLoc,
2127 QualType Type, const APValue &Value,
2128 ConstantExprKind Kind,
2129 SourceLocation SubobjectLoc,
2130 CheckedTemporaries &CheckedTemps);
2131
2132/// Check that this reference or pointer core constant expression is a valid
2133/// value for an address or reference constant expression. Return true if we
2134/// can fold this expression, whether or not it's a constant expression.
2135static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2136 QualType Type, const LValue &LVal,
2137 ConstantExprKind Kind,
2138 CheckedTemporaries &CheckedTemps) {
2139 bool IsReferenceType = Type->isReferenceType();
2140
2141 APValue::LValueBase Base = LVal.getLValueBase();
2142 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2143
2144 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2145 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2146
2147 // Additional restrictions apply in a template argument. We only enforce the
2148 // C++20 restrictions here; additional syntactic and semantic restrictions
2149 // are applied elsewhere.
2150 if (isTemplateArgument(Kind)) {
2151 int InvalidBaseKind = -1;
2152 StringRef Ident;
2153 if (Base.is<TypeInfoLValue>())
2154 InvalidBaseKind = 0;
2155 else if (isa_and_nonnull<StringLiteral>(BaseE))
2156 InvalidBaseKind = 1;
2157 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2158 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2159 InvalidBaseKind = 2;
2160 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2161 InvalidBaseKind = 3;
2162 Ident = PE->getIdentKindName();
2163 }
2164
2165 if (InvalidBaseKind != -1) {
2166 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2167 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2168 << Ident;
2169 return false;
2170 }
2171 }
2172
2173 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2174 if (FD->isConsteval()) {
2175 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2176 << !Type->isAnyPointerType();
2177 Info.Note(FD->getLocation(), diag::note_declared_at);
2178 return false;
2179 }
2180 }
2181
2182 // Check that the object is a global. Note that the fake 'this' object we
2183 // manufacture when checking potential constant expressions is conservatively
2184 // assumed to be global here.
2185 if (!IsGlobalLValue(Base)) {
2186 if (Info.getLangOpts().CPlusPlus11) {
2187 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2188 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2189 << BaseVD;
2190 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2191 if (VarD && VarD->isConstexpr()) {
2192 // Non-static local constexpr variables have unintuitive semantics:
2193 // constexpr int a = 1;
2194 // constexpr const int *p = &a;
2195 // ... is invalid because the address of 'a' is not constant. Suggest
2196 // adding a 'static' in this case.
2197 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2198 << VarD
2199 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2200 } else {
2201 NoteLValueLocation(Info, Base);
2202 }
2203 } else {
2204 Info.FFDiag(Loc);
2205 }
2206 // Don't allow references to temporaries to escape.
2207 return false;
2208 }
2209 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", 2211, __extension__ __PRETTY_FUNCTION__
))
2210 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", 2211, __extension__ __PRETTY_FUNCTION__
))
2211 "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", 2211, __extension__ __PRETTY_FUNCTION__
))
;
2212
2213 if (Base.is<DynamicAllocLValue>()) {
2214 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2215 << IsReferenceType << !Designator.Entries.empty();
2216 NoteLValueLocation(Info, Base);
2217 return false;
2218 }
2219
2220 if (BaseVD) {
2221 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2222 // Check if this is a thread-local variable.
2223 if (Var->getTLSKind())
2224 // FIXME: Diagnostic!
2225 return false;
2226
2227 // A dllimport variable never acts like a constant, unless we're
2228 // evaluating a value for use only in name mangling.
2229 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2230 // FIXME: Diagnostic!
2231 return false;
2232
2233 // In CUDA/HIP device compilation, only device side variables have
2234 // constant addresses.
2235 if (Info.getCtx().getLangOpts().CUDA &&
2236 Info.getCtx().getLangOpts().CUDAIsDevice &&
2237 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2238 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2239 !Var->hasAttr<CUDAConstantAttr>() &&
2240 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2241 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2242 Var->hasAttr<HIPManagedAttr>())
2243 return false;
2244 }
2245 }
2246 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2247 // __declspec(dllimport) must be handled very carefully:
2248 // We must never initialize an expression with the thunk in C++.
2249 // Doing otherwise would allow the same id-expression to yield
2250 // different addresses for the same function in different translation
2251 // units. However, this means that we must dynamically initialize the
2252 // expression with the contents of the import address table at runtime.
2253 //
2254 // The C language has no notion of ODR; furthermore, it has no notion of
2255 // dynamic initialization. This means that we are permitted to
2256 // perform initialization with the address of the thunk.
2257 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2258 FD->hasAttr<DLLImportAttr>())
2259 // FIXME: Diagnostic!
2260 return false;
2261 }
2262 } else if (const auto *MTE =
2263 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2264 if (CheckedTemps.insert(MTE).second) {
2265 QualType TempType = getType(Base);
2266 if (TempType.isDestructedType()) {
2267 Info.FFDiag(MTE->getExprLoc(),
2268 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2269 << TempType;
2270 return false;
2271 }
2272
2273 APValue *V = MTE->getOrCreateValue(false);
2274 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", 2274, __extension__ __PRETTY_FUNCTION__
))
;
2275 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2276 Info, MTE->getExprLoc(), TempType, *V,
2277 Kind, SourceLocation(), CheckedTemps))
2278 return false;
2279 }
2280 }
2281
2282 // Allow address constant expressions to be past-the-end pointers. This is
2283 // an extension: the standard requires them to point to an object.
2284 if (!IsReferenceType)
2285 return true;
2286
2287 // A reference constant expression must refer to an object.
2288 if (!Base) {
2289 // FIXME: diagnostic
2290 Info.CCEDiag(Loc);
2291 return true;
2292 }
2293
2294 // Does this refer one past the end of some object?
2295 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2296 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2297 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2298 NoteLValueLocation(Info, Base);
2299 }
2300
2301 return true;
2302}
2303
2304/// Member pointers are constant expressions unless they point to a
2305/// non-virtual dllimport member function.
2306static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2307 SourceLocation Loc,
2308 QualType Type,
2309 const APValue &Value,
2310 ConstantExprKind Kind) {
2311 const ValueDecl *Member = Value.getMemberPointerDecl();
2312 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2313 if (!FD)
2314 return true;
2315 if (FD->isConsteval()) {
2316 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2317 Info.Note(FD->getLocation(), diag::note_declared_at);
2318 return false;
2319 }
2320 return isForManglingOnly(Kind) || FD->isVirtual() ||
2321 !FD->hasAttr<DLLImportAttr>();
2322}
2323
2324/// Check that this core constant expression is of literal type, and if not,
2325/// produce an appropriate diagnostic.
2326static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2327 const LValue *This = nullptr) {
2328 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2329 return true;
2330
2331 // C++1y: A constant initializer for an object o [...] may also invoke
2332 // constexpr constructors for o and its subobjects even if those objects
2333 // are of non-literal class types.
2334 //
2335 // C++11 missed this detail for aggregates, so classes like this:
2336 // struct foo_t { union { int i; volatile int j; } u; };
2337 // are not (obviously) initializable like so:
2338 // __attribute__((__require_constant_initialization__))
2339 // static const foo_t x = {{0}};
2340 // because "i" is a subobject with non-literal initialization (due to the
2341 // volatile member of the union). See:
2342 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2343 // Therefore, we use the C++1y behavior.
2344 if (This && Info.EvaluatingDecl == This->getLValueBase())
2345 return true;
2346
2347 // Prvalue constant expressions must be of literal types.
2348 if (Info.getLangOpts().CPlusPlus11)
2349 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2350 << E->getType();
2351 else
2352 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2353 return false;
2354}
2355
2356static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2357 EvalInfo &Info, SourceLocation DiagLoc,
2358 QualType Type, const APValue &Value,
2359 ConstantExprKind Kind,
2360 SourceLocation SubobjectLoc,
2361 CheckedTemporaries &CheckedTemps) {
2362 if (!Value.hasValue()) {
2363 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2364 << true << Type;
2365 if (SubobjectLoc.isValid())
2366 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2367 return false;
2368 }
2369
2370 // We allow _Atomic(T) to be initialized from anything that T can be
2371 // initialized from.
2372 if (const AtomicType *AT = Type->getAs<AtomicType>())
2373 Type = AT->getValueType();
2374
2375 // Core issue 1454: For a literal constant expression of array or class type,
2376 // each subobject of its value shall have been initialized by a constant
2377 // expression.
2378 if (Value.isArray()) {
2379 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2380 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2381 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2382 Value.getArrayInitializedElt(I), Kind,
2383 SubobjectLoc, CheckedTemps))
2384 return false;
2385 }
2386 if (!Value.hasArrayFiller())
2387 return true;
2388 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2389 Value.getArrayFiller(), Kind, SubobjectLoc,
2390 CheckedTemps);
2391 }
2392 if (Value.isUnion() && Value.getUnionField()) {
2393 return CheckEvaluationResult(
2394 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2395 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2396 CheckedTemps);
2397 }
2398 if (Value.isStruct()) {
2399 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2400 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2401 unsigned BaseIndex = 0;
2402 for (const CXXBaseSpecifier &BS : CD->bases()) {
2403 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2404 Value.getStructBase(BaseIndex), Kind,
2405 BS.getBeginLoc(), CheckedTemps))
2406 return false;
2407 ++BaseIndex;
2408 }
2409 }
2410 for (const auto *I : RD->fields()) {
2411 if (I->isUnnamedBitfield())
2412 continue;
2413
2414 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2415 Value.getStructField(I->getFieldIndex()),
2416 Kind, I->getLocation(), CheckedTemps))
2417 return false;
2418 }
2419 }
2420
2421 if (Value.isLValue() &&
2422 CERK == CheckEvaluationResultKind::ConstantExpression) {
2423 LValue LVal;
2424 LVal.setFrom(Info.Ctx, Value);
2425 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2426 CheckedTemps);
2427 }
2428
2429 if (Value.isMemberPointer() &&
2430 CERK == CheckEvaluationResultKind::ConstantExpression)
2431 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2432
2433 // Everything else is fine.
2434 return true;
2435}
2436
2437/// Check that this core constant expression value is a valid value for a
2438/// constant expression. If not, report an appropriate diagnostic. Does not
2439/// check that the expression is of literal type.
2440static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2441 QualType Type, const APValue &Value,
2442 ConstantExprKind Kind) {
2443 // Nothing to check for a constant expression of type 'cv void'.
2444 if (Type->isVoidType())
2445 return true;
2446
2447 CheckedTemporaries CheckedTemps;
2448 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2449 Info, DiagLoc, Type, Value, Kind,
2450 SourceLocation(), CheckedTemps);
2451}
2452
2453/// Check that this evaluated value is fully-initialized and can be loaded by
2454/// an lvalue-to-rvalue conversion.
2455static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2456 QualType Type, const APValue &Value) {
2457 CheckedTemporaries CheckedTemps;
2458 return CheckEvaluationResult(
2459 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2460 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2461}
2462
2463/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2464/// "the allocated storage is deallocated within the evaluation".
2465static bool CheckMemoryLeaks(EvalInfo &Info) {
2466 if (!Info.HeapAllocs.empty()) {
2467 // We can still fold to a constant despite a compile-time memory leak,
2468 // so long as the heap allocation isn't referenced in the result (we check
2469 // that in CheckConstantExpression).
2470 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2471 diag::note_constexpr_memory_leak)
2472 << unsigned(Info.HeapAllocs.size() - 1);
2473 }
2474 return true;
2475}
2476
2477static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2478 // A null base expression indicates a null pointer. These are always
2479 // evaluatable, and they are false unless the offset is zero.
2480 if (!Value.getLValueBase()) {
2481 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2482 Result = !Value.getLValueOffset().isZero();
2483 return true;
2484 }
2485
2486 // We have a non-null base. These are generally known to be true, but if it's
2487 // a weak declaration it can be null at runtime.
2488 Result = true;
2489 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2490 return !Decl || !Decl->isWeak();
2491}
2492
2493static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2494 // TODO: This function should produce notes if it fails.
2495 switch (Val.getKind()) {
2496 case APValue::None:
2497 case APValue::Indeterminate:
2498 return false;
2499 case APValue::Int:
2500 Result = Val.getInt().getBoolValue();
2501 return true;
2502 case APValue::FixedPoint:
2503 Result = Val.getFixedPoint().getBoolValue();
2504 return true;
2505 case APValue::Float:
2506 Result = !Val.getFloat().isZero();
2507 return true;
2508 case APValue::ComplexInt:
2509 Result = Val.getComplexIntReal().getBoolValue() ||
2510 Val.getComplexIntImag().getBoolValue();
2511 return true;
2512 case APValue::ComplexFloat:
2513 Result = !Val.getComplexFloatReal().isZero() ||
2514 !Val.getComplexFloatImag().isZero();
2515 return true;
2516 case APValue::LValue:
2517 return EvalPointerValueAsBool(Val, Result);
2518 case APValue::MemberPointer:
2519 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2520 return false;
2521 }
2522 Result = Val.getMemberPointerDecl();
2523 return true;
2524 case APValue::Vector:
2525 case APValue::Array:
2526 case APValue::Struct:
2527 case APValue::Union:
2528 case APValue::AddrLabelDiff:
2529 return false;
2530 }
2531
2532 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "clang/lib/AST/ExprConstant.cpp"
, 2532)
;
2533}
2534
2535static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2536 EvalInfo &Info) {
2537 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 2537, __extension__ __PRETTY_FUNCTION__))
;
2538 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", 2538, __extension__ __PRETTY_FUNCTION__
))
;
2539 APValue Val;
2540 if (!Evaluate(Val, Info, E))
2541 return false;
2542 return HandleConversionToBool(Val, Result);
2543}
2544
2545template<typename T>
2546static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2547 const T &SrcValue, QualType DestType) {
2548 Info.CCEDiag(E, diag::note_constexpr_overflow)
2549 << SrcValue << DestType;
2550 return Info.noteUndefinedBehavior();
2551}
2552
2553static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2554 QualType SrcType, const APFloat &Value,
2555 QualType DestType, APSInt &Result) {
2556 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2557 // Determine whether we are converting to unsigned or signed.
2558 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2559
2560 Result = APSInt(DestWidth, !DestSigned);
2561 bool ignored;
2562 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2563 & APFloat::opInvalidOp)
2564 return HandleOverflow(Info, E, Value, DestType);
2565 return true;
2566}
2567
2568/// Get rounding mode to use in evaluation of the specified expression.
2569///
2570/// If rounding mode is unknown at compile time, still try to evaluate the
2571/// expression. If the result is exact, it does not depend on rounding mode.
2572/// So return "tonearest" mode instead of "dynamic".
2573static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2574 llvm::RoundingMode RM =
2575 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2576 if (RM == llvm::RoundingMode::Dynamic)
2577 RM = llvm::RoundingMode::NearestTiesToEven;
2578 return RM;
2579}
2580
2581/// Check if the given evaluation result is allowed for constant evaluation.
2582static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2583 APFloat::opStatus St) {
2584 // In a constant context, assume that any dynamic rounding mode or FP
2585 // exception state matches the default floating-point environment.
2586 if (Info.InConstantContext)
2587 return true;
2588
2589 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2590 if ((St & APFloat::opInexact) &&
2591 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2592 // Inexact result means that it depends on rounding mode. If the requested
2593 // mode is dynamic, the evaluation cannot be made in compile time.
2594 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2595 return false;
2596 }
2597
2598 if ((St != APFloat::opOK) &&
2599 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2600 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2601 FPO.getAllowFEnvAccess())) {
2602 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2603 return false;
2604 }
2605
2606 if ((St & APFloat::opStatus::opInvalidOp) &&
2607 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2608 // There is no usefully definable result.
2609 Info.FFDiag(E);
2610 return false;
2611 }
2612
2613 // FIXME: if:
2614 // - evaluation triggered other FP exception, and
2615 // - exception mode is not "ignore", and
2616 // - the expression being evaluated is not a part of global variable
2617 // initializer,
2618 // the evaluation probably need to be rejected.
2619 return true;
2620}
2621
2622static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2623 QualType SrcType, QualType DestType,
2624 APFloat &Result) {
2625 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", 2625, __extension__ __PRETTY_FUNCTION__
))
;
2626 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2627 APFloat::opStatus St;
2628 APFloat Value = Result;
2629 bool ignored;
2630 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2631 return checkFloatingPointResult(Info, E, St);
2632}
2633
2634static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2635 QualType DestType, QualType SrcType,
2636 const APSInt &Value) {
2637 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2638 // Figure out if this is a truncate, extend or noop cast.
2639 // If the input is signed, do a sign extend, noop, or truncate.
2640 APSInt Result = Value.extOrTrunc(DestWidth);
2641 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2642 if (DestType->isBooleanType())
2643 Result = Value.getBoolValue();
2644 return Result;
2645}
2646
2647static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2648 const FPOptions FPO,
2649 QualType SrcType, const APSInt &Value,
2650 QualType DestType, APFloat &Result) {
2651 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2652 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2653 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2654 return checkFloatingPointResult(Info, E, St);
2655}
2656
2657static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2658 APValue &Value, const FieldDecl *FD) {
2659 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", 2659, __extension__ __PRETTY_FUNCTION__
))
;
2660
2661 if (!Value.isInt()) {
2662 // Trying to store a pointer-cast-to-integer into a bitfield.
2663 // FIXME: In this case, we should provide the diagnostic for casting
2664 // a pointer to an integer.
2665 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", 2665, __extension__ __PRETTY_FUNCTION__
))
;
2666 Info.FFDiag(E);
2667 return false;
2668 }
2669
2670 APSInt &Int = Value.getInt();
2671 unsigned OldBitWidth = Int.getBitWidth();
2672 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2673 if (NewBitWidth < OldBitWidth)
2674 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2675 return true;
2676}
2677
2678static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2679 llvm::APInt &Res) {
2680 APValue SVal;
2681 if (!Evaluate(SVal, Info, E))
2682 return false;
2683 if (SVal.isInt()) {
2684 Res = SVal.getInt();
2685 return true;
2686 }
2687 if (SVal.isFloat()) {
2688 Res = SVal.getFloat().bitcastToAPInt();
2689 return true;
2690 }
2691 if (SVal.isVector()) {
2692 QualType VecTy = E->getType();
2693 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2694 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2695 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2696 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2697 Res = llvm::APInt::getZero(VecSize);
2698 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2699 APValue &Elt = SVal.getVectorElt(i);
2700 llvm::APInt EltAsInt;
2701 if (Elt.isInt()) {
2702 EltAsInt = Elt.getInt();
2703 } else if (Elt.isFloat()) {
2704 EltAsInt = Elt.getFloat().bitcastToAPInt();
2705 } else {
2706 // Don't try to handle vectors of anything other than int or float
2707 // (not sure if it's possible to hit this case).
2708 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2709 return false;
2710 }
2711 unsigned BaseEltSize = EltAsInt.getBitWidth();
2712 if (BigEndian)
2713 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2714 else
2715 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2716 }
2717 return true;
2718 }
2719 // Give up if the input isn't an int, float, or vector. For example, we
2720 // reject "(v4i16)(intptr_t)&a".
2721 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2722 return false;
2723}
2724
2725/// Perform the given integer operation, which is known to need at most BitWidth
2726/// bits, and check for overflow in the original type (if that type was not an
2727/// unsigned type).
2728template<typename Operation>
2729static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2730 const APSInt &LHS, const APSInt &RHS,
2731 unsigned BitWidth, Operation Op,
2732 APSInt &Result) {
2733 if (LHS.isUnsigned()) {
2734 Result = Op(LHS, RHS);
2735 return true;
2736 }
2737
2738 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2739 Result = Value.trunc(LHS.getBitWidth());
2740 if (Result.extend(BitWidth) != Value) {
2741 if (Info.checkingForUndefinedBehavior())
2742 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2743 diag::warn_integer_constant_overflow)
2744 << toString(Result, 10) << E->getType();
2745 return HandleOverflow(Info, E, Value, E->getType());
2746 }
2747 return true;
2748}
2749
2750/// Perform the given binary integer operation.
2751static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2752 BinaryOperatorKind Opcode, APSInt RHS,
2753 APSInt &Result) {
2754 switch (Opcode) {
2755 default:
2756 Info.FFDiag(E);
2757 return false;
2758 case BO_Mul:
2759 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2760 std::multiplies<APSInt>(), Result);
2761 case BO_Add:
2762 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2763 std::plus<APSInt>(), Result);
2764 case BO_Sub:
2765 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2766 std::minus<APSInt>(), Result);
2767 case BO_And: Result = LHS & RHS; return true;
2768 case BO_Xor: Result = LHS ^ RHS; return true;
2769 case BO_Or: Result = LHS | RHS; return true;
2770 case BO_Div:
2771 case BO_Rem:
2772 if (RHS == 0) {
2773 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2774 return false;
2775 }
2776 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2777 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2778 // this operation and gives the two's complement result.
2779 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2780 LHS.isMinSignedValue())
2781 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2782 E->getType());
2783 return true;
2784 case BO_Shl: {
2785 if (Info.getLangOpts().OpenCL)
2786 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2787 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2788 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2789 RHS.isUnsigned());
2790 else if (RHS.isSigned() && RHS.isNegative()) {
2791 // During constant-folding, a negative shift is an opposite shift. Such
2792 // a shift is not a constant expression.
2793 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2794 RHS = -RHS;
2795 goto shift_right;
2796 }
2797 shift_left:
2798 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2799 // the shifted type.
2800 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2801 if (SA != RHS) {
2802 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2803 << RHS << E->getType() << LHS.getBitWidth();
2804 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2805 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2806 // operand, and must not overflow the corresponding unsigned type.
2807 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2808 // E1 x 2^E2 module 2^N.
2809 if (LHS.isNegative())
2810 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2811 else if (LHS.countLeadingZeros() < SA)
2812 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2813 }
2814 Result = LHS << SA;
2815 return true;
2816 }
2817 case BO_Shr: {
2818 if (Info.getLangOpts().OpenCL)
2819 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2820 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2821 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2822 RHS.isUnsigned());
2823 else if (RHS.isSigned() && RHS.isNegative()) {
2824 // During constant-folding, a negative shift is an opposite shift. Such a
2825 // shift is not a constant expression.
2826 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2827 RHS = -RHS;
2828 goto shift_left;
2829 }
2830 shift_right:
2831 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2832 // shifted type.
2833 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2834 if (SA != RHS)
2835 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2836 << RHS << E->getType() << LHS.getBitWidth();
2837 Result = LHS >> SA;
2838 return true;
2839 }
2840
2841 case BO_LT: Result = LHS < RHS; return true;
2842 case BO_GT: Result = LHS > RHS; return true;
2843 case BO_LE: Result = LHS <= RHS; return true;
2844 case BO_GE: Result = LHS >= RHS; return true;
2845 case BO_EQ: Result = LHS == RHS; return true;
2846 case BO_NE: Result = LHS != RHS; return true;
2847 case BO_Cmp:
2848 llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere"
, "clang/lib/AST/ExprConstant.cpp", 2848)
;
2849 }
2850}
2851
2852/// Perform the given binary floating-point operation, in-place, on LHS.
2853static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2854 APFloat &LHS, BinaryOperatorKind Opcode,
2855 const APFloat &RHS) {
2856 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2857 APFloat::opStatus St;
2858 switch (Opcode) {
2859 default:
2860 Info.FFDiag(E);
2861 return false;
2862 case BO_Mul:
2863 St = LHS.multiply(RHS, RM);
2864 break;
2865 case BO_Add:
2866 St = LHS.add(RHS, RM);
2867 break;
2868 case BO_Sub:
2869 St = LHS.subtract(RHS, RM);
2870 break;
2871 case BO_Div:
2872 // [expr.mul]p4:
2873 // If the second operand of / or % is zero the behavior is undefined.
2874 if (RHS.isZero())
2875 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2876 St = LHS.divide(RHS, RM);
2877 break;
2878 }
2879
2880 // [expr.pre]p4:
2881 // If during the evaluation of an expression, the result is not
2882 // mathematically defined [...], the behavior is undefined.
2883 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2884 if (LHS.isNaN()) {
2885 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2886 return Info.noteUndefinedBehavior();
2887 }
2888
2889 return checkFloatingPointResult(Info, E, St);
2890}
2891
2892static bool handleLogicalOpForVector(const APInt &LHSValue,
2893 BinaryOperatorKind Opcode,
2894 const APInt &RHSValue, APInt &Result) {
2895 bool LHS = (LHSValue != 0);
2896 bool RHS = (RHSValue != 0);
2897
2898 if (Opcode == BO_LAnd)
2899 Result = LHS && RHS;
2900 else
2901 Result = LHS || RHS;
2902 return true;
2903}
2904static bool handleLogicalOpForVector(const APFloat &LHSValue,
2905 BinaryOperatorKind Opcode,
2906 const APFloat &RHSValue, APInt &Result) {
2907 bool LHS = !LHSValue.isZero();
2908 bool RHS = !RHSValue.isZero();
2909
2910 if (Opcode == BO_LAnd)
2911 Result = LHS && RHS;
2912 else
2913 Result = LHS || RHS;
2914 return true;
2915}
2916
2917static bool handleLogicalOpForVector(const APValue &LHSValue,
2918 BinaryOperatorKind Opcode,
2919 const APValue &RHSValue, APInt &Result) {
2920 // The result is always an int type, however operands match the first.
2921 if (LHSValue.getKind() == APValue::Int)
2922 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2923 RHSValue.getInt(), Result);
2924 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", 2924, __extension__ __PRETTY_FUNCTION__
))
;
2925 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2926 RHSValue.getFloat(), Result);
2927}
2928
2929template <typename APTy>
2930static bool
2931handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2932 const APTy &RHSValue, APInt &Result) {
2933 switch (Opcode) {
2934 default:
2935 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "clang/lib/AST/ExprConstant.cpp", 2935)
;
2936 case BO_EQ:
2937 Result = (LHSValue == RHSValue);
2938 break;
2939 case BO_NE:
2940 Result = (LHSValue != RHSValue);
2941 break;
2942 case BO_LT:
2943 Result = (LHSValue < RHSValue);
2944 break;
2945 case BO_GT:
2946 Result = (LHSValue > RHSValue);
2947 break;
2948 case BO_LE:
2949 Result = (LHSValue <= RHSValue);
2950 break;
2951 case BO_GE:
2952 Result = (LHSValue >= RHSValue);
2953 break;
2954 }
2955
2956 // The boolean operations on these vector types use an instruction that
2957 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2958 // to -1 to make sure that we produce the correct value.
2959 Result.negate();
2960
2961 return true;
2962}
2963
2964static bool handleCompareOpForVector(const APValue &LHSValue,
2965 BinaryOperatorKind Opcode,
2966 const APValue &RHSValue, APInt &Result) {
2967 // The result is always an int type, however operands match the first.
2968 if (LHSValue.getKind() == APValue::Int)
2969 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2970 RHSValue.getInt(), Result);
2971 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", 2971, __extension__ __PRETTY_FUNCTION__
))
;
2972 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2973 RHSValue.getFloat(), Result);
2974}
2975
2976// Perform binary operations for vector types, in place on the LHS.
2977static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2978 BinaryOperatorKind Opcode,
2979 APValue &LHSValue,
2980 const APValue &RHSValue) {
2981 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", 2982, __extension__ __PRETTY_FUNCTION__
))
2982 "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", 2982, __extension__ __PRETTY_FUNCTION__
))
;
2983
2984 const auto *VT = E->getType()->castAs<VectorType>();
2985 unsigned NumElements = VT->getNumElements();
2986 QualType EltTy = VT->getElementType();
2987
2988 // In the cases (typically C as I've observed) where we aren't evaluating
2989 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2990 // just give up.
2991 if (!LHSValue.isVector()) {
2992 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", 2993, __extension__ __PRETTY_FUNCTION__
))
2993 "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", 2993, __extension__ __PRETTY_FUNCTION__
))
;
2994 Info.FFDiag(E);
2995 return false;
2996 }
2997
2998 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", 2999, __extension__ __PRETTY_FUNCTION__
))
2999 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", 2999, __extension__ __PRETTY_FUNCTION__
))
;
3000
3001 SmallVector<APValue, 4> ResultElements;
3002
3003 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3004 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3005 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3006
3007 if (EltTy->isIntegerType()) {
3008 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3009 EltTy->isUnsignedIntegerType()};
3010 bool Success = true;
3011
3012 if (BinaryOperator::isLogicalOp(Opcode))
3013 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3014 else if (BinaryOperator::isComparisonOp(Opcode))
3015 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3016 else
3017 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3018 RHSElt.getInt(), EltResult);
3019
3020 if (!Success) {
3021 Info.FFDiag(E);
3022 return false;
3023 }
3024 ResultElements.emplace_back(EltResult);
3025
3026 } else if (EltTy->isFloatingType()) {
3027 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", 3029, __extension__ __PRETTY_FUNCTION__
))
3028 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", 3029, __extension__ __PRETTY_FUNCTION__
))
3029 "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", 3029, __extension__ __PRETTY_FUNCTION__
))
;
3030 APFloat LHSFloat = LHSElt.getFloat();
3031
3032 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3033 RHSElt.getFloat())) {
3034 Info.FFDiag(E);
3035 return false;
3036 }
3037
3038 ResultElements.emplace_back(LHSFloat);
3039 }
3040 }
3041
3042 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3043 return true;
3044}
3045
3046/// Cast an lvalue referring to a base subobject to a derived class, by
3047/// truncating the lvalue's path to the given length.
3048static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3049 const RecordDecl *TruncatedType,
3050 unsigned TruncatedElements) {
3051 SubobjectDesignator &D = Result.Designator;
3052
3053 // Check we actually point to a derived class object.
3054 if (TruncatedElements == D.Entries.size())
3055 return true;
3056 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", 3057, __extension__ __PRETTY_FUNCTION__
))
3057 "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", 3057, __extension__ __PRETTY_FUNCTION__
))
;
3058 if (!Result.checkSubobject(Info, E, CSK_Derived))
3059 return false;
3060
3061 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3062 const RecordDecl *RD = TruncatedType;
3063 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3064 if (RD->isInvalidDecl()) return false;
3065 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3066 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3067 if (isVirtualBaseClass(D.Entries[I]))
3068 Result.Offset -= Layout.getVBaseClassOffset(Base);
3069 else
3070 Result.Offset -= Layout.getBaseClassOffset(Base);
3071 RD = Base;
3072 }
3073 D.Entries.resize(TruncatedElements);
3074 return true;
3075}
3076
3077static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3078 const CXXRecordDecl *Derived,
3079 const CXXRecordDecl *Base,
3080 const ASTRecordLayout *RL = nullptr) {
3081 if (!RL) {
3082 if (Derived->isInvalidDecl()) return false;
3083 RL = &Info.Ctx.getASTRecordLayout(Derived);
3084 }
3085
3086 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3087 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3088 return true;
3089}
3090
3091static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3092 const CXXRecordDecl *DerivedDecl,
3093 const CXXBaseSpecifier *Base) {
3094 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3095
3096 if (!Base->isVirtual())
3097 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3098
3099 SubobjectDesignator &D = Obj.Designator;
3100 if (D.Invalid)
3101 return false;
3102
3103 // Extract most-derived object and corresponding type.
3104 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3105 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3106 return false;
3107
3108 // Find the virtual base class.
3109 if (DerivedDecl->isInvalidDecl()) return false;
3110 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3111 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3112 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3113 return true;
3114}
3115
3116static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3117 QualType Type, LValue &Result) {
3118 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3119 PathE = E->path_end();
3120 PathI != PathE; ++PathI) {
3121 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3122 *PathI))
3123 return false;
3124 Type = (*PathI)->getType();
3125 }
3126 return true;
3127}
3128
3129/// Cast an lvalue referring to a derived class to a known base subobject.
3130static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3131 const CXXRecordDecl *DerivedRD,
3132 const CXXRecordDecl *BaseRD) {
3133 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3134 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3135 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3136 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", 3136)
;
3137
3138 for (CXXBasePathElement &Elem : Paths.front())
3139 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3140 return false;
3141 return true;
3142}
3143
3144/// Update LVal to refer to the given field, which must be a member of the type
3145/// currently described by LVal.
3146static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3147 const FieldDecl *FD,
3148 const ASTRecordLayout *RL = nullptr) {
3149 if (!RL) {
3150 if (FD->getParent()->isInvalidDecl()) return false;
3151 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3152 }
3153
3154 unsigned I = FD->getFieldIndex();
3155 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3156 LVal.addDecl(Info, E, FD);
3157 return true;
3158}
3159
3160/// Update LVal to refer to the given indirect field.
3161static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3162 LValue &LVal,
3163 const IndirectFieldDecl *IFD) {
3164 for (const auto *C : IFD->chain())
3165 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3166 return false;
3167 return true;
3168}
3169
3170/// Get the size of the given type in char units.
3171static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3172 QualType Type, CharUnits &Size) {
3173 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3174 // extension.
3175 if (Type->isVoidType() || Type->isFunctionType()) {
3176 Size = CharUnits::One();
3177 return true;
3178 }
3179
3180 if (Type->isDependentType()) {
3181 Info.FFDiag(Loc);
3182 return false;
3183 }
3184
3185 if (!Type->isConstantSizeType()) {
3186 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3187 // FIXME: Better diagnostic.
3188 Info.FFDiag(Loc);
3189 return false;
3190 }
3191
3192 Size = Info.Ctx.getTypeSizeInChars(Type);
3193 return true;
3194}
3195
3196/// Update a pointer value to model pointer arithmetic.
3197/// \param Info - Information about the ongoing evaluation.
3198/// \param E - The expression being evaluated, for diagnostic purposes.
3199/// \param LVal - The pointer value to be updated.
3200/// \param EltTy - The pointee type represented by LVal.
3201/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3202static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3203 LValue &LVal, QualType EltTy,
3204 APSInt Adjustment) {
3205 CharUnits SizeOfPointee;
3206 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
29
Called C++ object pointer is null
3207 return false;
3208
3209 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3210 return true;
3211}
3212
3213static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3214 LValue &LVal, QualType EltTy,
3215 int64_t Adjustment) {
3216 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
27
Passing null pointer value via 2nd parameter 'E'
28
Calling 'HandleLValueArrayAdjustment'
3217 APSInt::get(Adjustment));
3218}
3219
3220/// Update an lvalue to refer to a component of a complex number.
3221/// \param Info - Information about the ongoing evaluation.
3222/// \param LVal - The lvalue to be updated.
3223/// \param EltTy - The complex number's component type.
3224/// \param Imag - False for the real component, true for the imaginary.
3225static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3226 LValue &LVal, QualType EltTy,
3227 bool Imag) {
3228 if (Imag) {
3229 CharUnits SizeOfComponent;
3230 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3231 return false;
3232 LVal.Offset += SizeOfComponent;
3233 }
3234 LVal.addComplex(Info, E, EltTy, Imag);
3235 return true;
3236}
3237
3238/// Try to evaluate the initializer for a variable declaration.
3239///
3240/// \param Info Information about the ongoing evaluation.
3241/// \param E An expression to be used when printing diagnostics.
3242/// \param VD The variable whose initializer should be obtained.
3243/// \param Version The version of the variable within the frame.
3244/// \param Frame The frame in which the variable was created. Must be null
3245/// if this variable is not local to the evaluation.
3246/// \param Result Filled in with a pointer to the value of the variable.
3247static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3248 const VarDecl *VD, CallStackFrame *Frame,
3249 unsigned Version, APValue *&Result) {
3250 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3251
3252 // If this is a local variable, dig out its value.
3253 if (Frame) {
3254 Result = Frame->getTemporary(VD, Version);
3255 if (Result)
3256 return true;
3257
3258 if (!isa<ParmVarDecl>(VD)) {
3259 // Assume variables referenced within a lambda's call operator that were
3260 // not declared within the call operator are captures and during checking
3261 // of a potential constant expression, assume they are unknown constant
3262 // expressions.
3263 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", 3265, __extension__ __PRETTY_FUNCTION__
))
3264 (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", 3265, __extension__ __PRETTY_FUNCTION__
))
3265 "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", 3265, __extension__ __PRETTY_FUNCTION__
))
;
3266 if (Info.checkingPotentialConstantExpression())
3267 return false;
3268 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3269 // still reachable at all?
3270 Info.FFDiag(E->getBeginLoc(),
3271 diag::note_unimplemented_constexpr_lambda_feature_ast)
3272 << "captures not currently allowed";
3273 return false;
3274 }
3275 }
3276
3277 // If we're currently evaluating the initializer of this declaration, use that
3278 // in-flight value.
3279 if (Info.EvaluatingDecl == Base) {
3280 Result = Info.EvaluatingDeclValue;
3281 return true;
3282 }
3283
3284 if (isa<ParmVarDecl>(VD)) {
3285 // Assume parameters of a potential constant expression are usable in
3286 // constant expressions.
3287 if (!Info.checkingPotentialConstantExpression() ||
3288 !Info.CurrentCall->Callee ||
3289 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3290 if (Info.getLangOpts().CPlusPlus11) {
3291 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3292 << VD;
3293 NoteLValueLocation(Info, Base);
3294 } else {
3295 Info.FFDiag(E);
3296 }
3297 }
3298 return false;
3299 }
3300
3301 // Dig out the initializer, and use the declaration which it's attached to.
3302 // FIXME: We should eventually check whether the variable has a reachable
3303 // initializing declaration.
3304 const Expr *Init = VD->getAnyInitializer(VD);
3305 if (!Init) {
3306 // Don't diagnose during potential constant expression checking; an
3307 // initializer might be added later.
3308 if (!Info.checkingPotentialConstantExpression()) {
3309 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3310 << VD;
3311 NoteLValueLocation(Info, Base);
3312 }
3313 return false;
3314 }
3315
3316 if (Init->isValueDependent()) {
3317 // The DeclRefExpr is not value-dependent, but the variable it refers to
3318 // has a value-dependent initializer. This should only happen in
3319 // constant-folding cases, where the variable is not actually of a suitable
3320 // type for use in a constant expression (otherwise the DeclRefExpr would
3321 // have been value-dependent too), so diagnose that.
3322 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", 3322, __extension__ __PRETTY_FUNCTION__
))
;
3323 if (!Info.checkingPotentialConstantExpression()) {
3324 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3325 ? diag::note_constexpr_ltor_non_constexpr
3326 : diag::note_constexpr_ltor_non_integral, 1)
3327 << VD << VD->getType();
3328 NoteLValueLocation(Info, Base);
3329 }
3330 return false;
3331 }
3332
3333 // Check that we can fold the initializer. In C++, we will have already done
3334 // this in the cases where it matters for conformance.
3335 if (!VD->evaluateValue()) {
3336 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3337 NoteLValueLocation(Info, Base);
3338 return false;
3339 }
3340
3341 // Check that the variable is actually usable in constant expressions. For a
3342 // const integral variable or a reference, we might have a non-constant
3343 // initializer that we can nonetheless evaluate the initializer for. Such
3344 // variables are not usable in constant expressions. In C++98, the
3345 // initializer also syntactically needs to be an ICE.
3346 //
3347 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3348 // expressions here; doing so would regress diagnostics for things like
3349 // reading from a volatile constexpr variable.
3350 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3351 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3352 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3353 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3354 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3355 NoteLValueLocation(Info, Base);
3356 }
3357
3358 // Never use the initializer of a weak variable, not even for constant
3359 // folding. We can't be sure that this is the definition that will be used.
3360 if (VD->isWeak()) {
3361 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3362 NoteLValueLocation(Info, Base);
3363 return false;
3364 }
3365
3366 Result = VD->getEvaluatedValue();
3367 return true;
3368}
3369
3370/// Get the base index of the given base class within an APValue representing
3371/// the given derived class.
3372static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3373 const CXXRecordDecl *Base) {
3374 Base = Base->getCanonicalDecl();
3375 unsigned Index = 0;
3376 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3377 E = Derived->bases_end(); I != E; ++I, ++Index) {
3378 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3379 return Index;
3380 }
3381
3382 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", 3382)
;
3383}
3384
3385/// Extract the value of a character from a string literal.
3386static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3387 uint64_t Index) {
3388 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", 3389, __extension__ __PRETTY_FUNCTION__
))
3389 "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", 3389, __extension__ __PRETTY_FUNCTION__
))
;
3390
3391 // FIXME: Support MakeStringConstant
3392 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3393 std::string Str;
3394 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3395 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", 3395, __extension__ __PRETTY_FUNCTION__
))
;
3396 return APSInt::getUnsigned(Str.c_str()[Index]);
3397 }
3398
3399 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3400 Lit = PE->getFunctionName();
3401 const StringLiteral *S = cast<StringLiteral>(Lit);
3402 const ConstantArrayType *CAT =
3403 Info.Ctx.getAsConstantArrayType(S->getType());
3404 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", 3404, __extension__ __PRETTY_FUNCTION__
))
;
3405 QualType CharType = CAT->getElementType();
3406 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", 3406, __extension__ __PRETTY_FUNCTION__
))
;
3407
3408 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3409 CharType->isUnsignedIntegerType());
3410 if (Index < S->getLength())
3411 Value = S->getCodeUnit(Index);
3412 return Value;
3413}
3414
3415// Expand a string literal into an array of characters.
3416//
3417// FIXME: This is inefficient; we should probably introduce something similar
3418// to the LLVM ConstantDataArray to make this cheaper.
3419static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3420 APValue &Result,
3421 QualType AllocType = QualType()) {
3422 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3423 AllocType.isNull() ? S->getType() : AllocType);
3424 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", 3424, __extension__ __PRETTY_FUNCTION__
))
;
3425 QualType CharType = CAT->getElementType();
3426 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", 3426, __extension__ __PRETTY_FUNCTION__
))
;
3427
3428 unsigned Elts = CAT->getSize().getZExtValue();
3429 Result = APValue(APValue::UninitArray(),
3430 std::min(S->getLength(), Elts), Elts);
3431 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3432 CharType->isUnsignedIntegerType());
3433 if (Result.hasArrayFiller())
3434 Result.getArrayFiller() = APValue(Value);
3435 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3436 Value = S->getCodeUnit(I);
3437 Result.getArrayInitializedElt(I) = APValue(Value);
3438 }
3439}
3440
3441// Expand an array so that it has more than Index filled elements.
3442static void expandArray(APValue &Array, unsigned Index) {
3443 unsigned Size = Array.getArraySize();
3444 assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail
("Index < Size", "clang/lib/AST/ExprConstant.cpp", 3444, __extension__
__PRETTY_FUNCTION__))
;
3445
3446 // Always at least double the number of elements for which we store a value.
3447 unsigned OldElts = Array.getArrayInitializedElts();
3448 unsigned NewElts = std::max(Index+1, OldElts * 2);
3449 NewElts = std::min(Size, std::max(NewElts, 8u));
3450
3451 // Copy the data across.
3452 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3453 for (unsigned I = 0; I != OldElts; ++I)
3454 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3455 for (unsigned I = OldElts; I != NewElts; ++I)
3456 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3457 if (NewValue.hasArrayFiller())
3458 NewValue.getArrayFiller() = Array.getArrayFiller();
3459 Array.swap(NewValue);
3460}
3461
3462/// Determine whether a type would actually be read by an lvalue-to-rvalue
3463/// conversion. If it's of class type, we may assume that the copy operation
3464/// is trivial. Note that this is never true for a union type with fields
3465/// (because the copy always "reads" the active member) and always true for
3466/// a non-class type.
3467static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3468static bool isReadByLvalueToRvalueConversion(QualType T) {
3469 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3470 return !RD || isReadByLvalueToRvalueConversion(RD);
3471}
3472static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3473 // FIXME: A trivial copy of a union copies the object representation, even if
3474 // the union is empty.
3475 if (RD->isUnion())
3476 return !RD->field_empty();
3477 if (RD->isEmpty())
3478 return false;
3479
3480 for (auto *Field : RD->fields())
3481 if (!Field->isUnnamedBitfield() &&
3482 isReadByLvalueToRvalueConversion(Field->getType()))
3483 return true;
3484
3485 for (auto &BaseSpec : RD->bases())
3486 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3487 return true;
3488
3489 return false;
3490}
3491
3492/// Diagnose an attempt to read from any unreadable field within the specified
3493/// type, which might be a class type.
3494static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3495 QualType T) {
3496 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3497 if (!RD)
3498 return false;
3499
3500 if (!RD->hasMutableFields())
3501 return false;
3502
3503 for (auto *Field : RD->fields()) {
3504 // If we're actually going to read this field in some way, then it can't
3505 // be mutable. If we're in a union, then assigning to a mutable field
3506 // (even an empty one) can change the active member, so that's not OK.
3507 // FIXME: Add core issue number for the union case.
3508 if (Field->isMutable() &&
3509 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3510 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3511 Info.Note(Field->getLocation(), diag::note_declared_at);
3512 return true;
3513 }
3514
3515 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3516 return true;
3517 }
3518
3519 for (auto &BaseSpec : RD->bases())
3520 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3521 return true;
3522
3523 // All mutable fields were empty, and thus not actually read.
3524 return false;
3525}
3526
3527static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3528 APValue::LValueBase Base,
3529 bool MutableSubobject = false) {
3530 // A temporary or transient heap allocation we created.
3531 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3532 return true;
3533
3534 switch (Info.IsEvaluatingDecl) {
3535 case EvalInfo::EvaluatingDeclKind::None:
3536 return false;
3537
3538 case EvalInfo::EvaluatingDeclKind::Ctor:
3539 // The variable whose initializer we're evaluating.
3540 if (Info.EvaluatingDecl == Base)
3541 return true;
3542
3543 // A temporary lifetime-extended by the variable whose initializer we're
3544 // evaluating.
3545 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3546 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3547 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3548 return false;
3549
3550 case EvalInfo::EvaluatingDeclKind::Dtor:
3551 // C++2a [expr.const]p6:
3552 // [during constant destruction] the lifetime of a and its non-mutable
3553 // subobjects (but not its mutable subobjects) [are] considered to start
3554 // within e.
3555 if (MutableSubobject || Base != Info.EvaluatingDecl)
3556 return false;
3557 // FIXME: We can meaningfully extend this to cover non-const objects, but
3558 // we will need special handling: we should be able to access only
3559 // subobjects of such objects that are themselves declared const.
3560 QualType T = getType(Base);
3561 return T.isConstQualified() || T->isReferenceType();
3562 }
3563
3564 llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind"
, "clang/lib/AST/ExprConstant.cpp", 3564)
;
3565}
3566
3567namespace {
3568/// A handle to a complete object (an object that is not a subobject of
3569/// another object).
3570struct CompleteObject {
3571 /// The identity of the object.
3572 APValue::LValueBase Base;
3573 /// The value of the complete object.
3574 APValue *Value;
3575 /// The type of the complete object.
3576 QualType Type;
3577
3578 CompleteObject() : Value(nullptr) {}
3579 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3580 : Base(Base), Value(Value), Type(Type) {}
3581
3582 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3583 // If this isn't a "real" access (eg, if it's just accessing the type
3584 // info), allow it. We assume the type doesn't change dynamically for
3585 // subobjects of constexpr objects (even though we'd hit UB here if it
3586 // did). FIXME: Is this right?
3587 if (!isAnyAccess(AK))
3588 return true;
3589
3590 // In C++14 onwards, it is permitted to read a mutable member whose
3591 // lifetime began within the evaluation.
3592 // FIXME: Should we also allow this in C++11?
3593 if (!Info.getLangOpts().CPlusPlus14)
3594 return false;
3595 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3596 }
3597
3598 explicit operator bool() const { return !Type.isNull(); }
3599};
3600} // end anonymous namespace
3601
3602static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3603 bool IsMutable = false) {
3604 // C++ [basic.type.qualifier]p1:
3605 // - A const object is an object of type const T or a non-mutable subobject
3606 // of a const object.
3607 if (ObjType.isConstQualified() && !IsMutable)
3608 SubobjType.addConst();
3609 // - A volatile object is an object of type const T or a subobject of a
3610 // volatile object.
3611 if (ObjType.isVolatileQualified())
3612 SubobjType.addVolatile();
3613 return SubobjType;
3614}
3615
3616/// Find the designated sub-object of an rvalue.
3617template<typename SubobjectHandler>
3618typename SubobjectHandler::result_type
3619findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3620 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3621 if (Sub.Invalid)
3622 // A diagnostic will have already been produced.
3623 return handler.failed();
3624 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3625 if (Info.getLangOpts().CPlusPlus11)
3626 Info.FFDiag(E, Sub.isOnePastTheEnd()
3627 ? diag::note_constexpr_access_past_end
3628 : diag::note_constexpr_access_unsized_array)
3629 << handler.AccessKind;
3630 else
3631 Info.FFDiag(E);
3632 return handler.failed();
3633 }
3634
3635 APValue *O = Obj.Value;
3636 QualType ObjType = Obj.Type;
3637 const FieldDecl *LastField = nullptr;
3638 const FieldDecl *VolatileField = nullptr;
3639
3640 // Walk the designator's path to find the subobject.
3641 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3642 // Reading an indeterminate value is undefined, but assigning over one is OK.
3643 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3644 (O->isIndeterminate() &&
3645 !isValidIndeterminateAccess(handler.AccessKind))) {
3646 if (!Info.checkingPotentialConstantExpression())
3647 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3648 << handler.AccessKind << O->isIndeterminate();
3649 return handler.failed();
3650 }
3651
3652 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3653 // const and volatile semantics are not applied on an object under
3654 // {con,de}struction.
3655 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3656 ObjType->isRecordType() &&
3657 Info.isEvaluatingCtorDtor(
3658 Obj.Base,
3659 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3660 ConstructionPhase::None) {
3661 ObjType = Info.Ctx.getCanonicalType(ObjType);
3662 ObjType.removeLocalConst();
3663 ObjType.removeLocalVolatile();
3664 }
3665
3666 // If this is our last pass, check that the final object type is OK.
3667 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3668 // Accesses to volatile objects are prohibited.
3669 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3670 if (Info.getLangOpts().CPlusPlus) {
3671 int DiagKind;
3672 SourceLocation Loc;
3673 const NamedDecl *Decl = nullptr;
3674 if (VolatileField) {
3675 DiagKind = 2;
3676 Loc = VolatileField->getLocation();
3677 Decl = VolatileField;
3678 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3679 DiagKind = 1;
3680 Loc = VD->getLocation();
3681 Decl = VD;
3682 } else {
3683 DiagKind = 0;
3684 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3685 Loc = E->getExprLoc();
3686 }
3687 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3688 << handler.AccessKind << DiagKind << Decl;
3689 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3690 } else {
3691 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3692 }
3693 return handler.failed();
3694 }
3695
3696 // If we are reading an object of class type, there may still be more
3697 // things we need to check: if there are any mutable subobjects, we
3698 // cannot perform this read. (This only happens when performing a trivial
3699 // copy or assignment.)
3700 if (ObjType->isRecordType() &&
3701 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3702 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3703 return handler.failed();
3704 }
3705
3706 if (I == N) {
3707 if (!handler.found(*O, ObjType))
3708 return false;
3709
3710 // If we modified a bit-field, truncate it to the right width.
3711 if (isModification(handler.AccessKind) &&
3712 LastField && LastField->isBitField() &&
3713 !truncateBitfieldValue(Info, E, *O, LastField))
3714 return false;
3715
3716 return true;
3717 }
3718
3719 LastField = nullptr;
3720 if (ObjType->isArrayType()) {
3721 // Next subobject is an array element.
3722 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3723 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", 3723, __extension__ __PRETTY_FUNCTION__
))
;
3724 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725 if (CAT->getSize().ule(Index)) {
3726 // Note, it should not be possible to form a pointer with a valid
3727 // designator which points more than one past the end of the array.
3728 if (Info.getLangOpts().CPlusPlus11)
3729 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730 << handler.AccessKind;
3731 else
3732 Info.FFDiag(E);
3733 return handler.failed();
3734 }
3735
3736 ObjType = CAT->getElementType();
3737
3738 if (O->getArrayInitializedElts() > Index)
3739 O = &O->getArrayInitializedElt(Index);
3740 else if (!isRead(handler.AccessKind)) {
3741 expandArray(*O, Index);
3742 O = &O->getArrayInitializedElt(Index);
3743 } else
3744 O = &O->getArrayFiller();
3745 } else if (ObjType->isAnyComplexType()) {
3746 // Next subobject is a complex number.
3747 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3748 if (Index > 1) {
3749 if (Info.getLangOpts().CPlusPlus11)
3750 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3751 << handler.AccessKind;
3752 else
3753 Info.FFDiag(E);
3754 return handler.failed();
3755 }
3756
3757 ObjType = getSubobjectType(
3758 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3759
3760 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", 3760, __extension__ __PRETTY_FUNCTION__
))
;
3761 if (O->isComplexInt()) {
3762 return handler.found(Index ? O->getComplexIntImag()
3763 : O->getComplexIntReal(), ObjType);
3764 } else {
3765 assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0)
: __assert_fail ("O->isComplexFloat()", "clang/lib/AST/ExprConstant.cpp"
, 3765, __extension__ __PRETTY_FUNCTION__))
;
3766 return handler.found(Index ? O->getComplexFloatImag()
3767 : O->getComplexFloatReal(), ObjType);
3768 }
3769 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3770 if (Field->isMutable() &&
3771 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3772 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3773 << handler.AccessKind << Field;
3774 Info.Note(Field->getLocation(), diag::note_declared_at);
3775 return handler.failed();
3776 }
3777
3778 // Next subobject is a class, struct or union field.
3779 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3780 if (RD->isUnion()) {
3781 const FieldDecl *UnionField = O->getUnionField();
3782 if (!UnionField ||
3783 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3784 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3785 // Placement new onto an inactive union member makes it active.
3786 O->setUnion(Field, APValue());
3787 } else {
3788 // FIXME: If O->getUnionValue() is absent, report that there's no
3789 // active union member rather than reporting the prior active union
3790 // member. We'll need to fix nullptr_t to not use APValue() as its
3791 // representation first.
3792 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3793 << handler.AccessKind << Field << !UnionField << UnionField;
3794 return handler.failed();
3795 }
3796 }
3797 O = &O->getUnionValue();
3798 } else
3799 O = &O->getStructField(Field->getFieldIndex());
3800
3801 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3802 LastField = Field;
3803 if (Field->getType().isVolatileQualified())
3804 VolatileField = Field;
3805 } else {
3806 // Next subobject is a base class.
3807 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3808 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3809 O = &O->getStructBase(getBaseIndex(Derived, Base));
3810
3811 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3812 }
3813 }
3814}
3815
3816namespace {
3817struct ExtractSubobjectHandler {
3818 EvalInfo &Info;
3819 const Expr *E;
3820 APValue &Result;
3821 const AccessKinds AccessKind;
3822
3823 typedef bool result_type;
3824 bool failed() { return false; }
3825 bool found(APValue &Subobj, QualType SubobjType) {
3826 Result = Subobj;
3827 if (AccessKind == AK_ReadObjectRepresentation)
3828 return true;
3829 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3830 }
3831 bool found(APSInt &Value, QualType SubobjType) {
3832 Result = APValue(Value);
3833 return true;
3834 }
3835 bool found(APFloat &Value, QualType SubobjType) {
3836 Result = APValue(Value);
3837 return true;
3838 }
3839};
3840} // end anonymous namespace
3841
3842/// Extract the designated sub-object of an rvalue.
3843static bool extractSubobject(EvalInfo &Info, const Expr *E,
3844 const CompleteObject &Obj,
3845 const SubobjectDesignator &Sub, APValue &Result,
3846 AccessKinds AK = AK_Read) {
3847 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", 3847, __extension__ __PRETTY_FUNCTION__
))
;
3848 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3849 return findSubobject(Info, E, Obj, Sub, Handler);
3850}
3851
3852namespace {
3853struct ModifySubobjectHandler {
3854 EvalInfo &Info;
3855 APValue &NewVal;
3856 const Expr *E;
3857
3858 typedef bool result_type;
3859 static const AccessKinds AccessKind = AK_Assign;
3860
3861 bool checkConst(QualType QT) {
3862 // Assigning to a const object has undefined behavior.
3863 if (QT.isConstQualified()) {
3864 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3865 return false;
3866 }
3867 return true;
3868 }
3869
3870 bool failed() { return false; }
3871 bool found(APValue &Subobj, QualType SubobjType) {
3872 if (!checkConst(SubobjType))
3873 return false;
3874 // We've been given ownership of NewVal, so just swap it in.
3875 Subobj.swap(NewVal);
3876 return true;
3877 }
3878 bool found(APSInt &Value, QualType SubobjType) {
3879 if (!checkConst(SubobjType))
3880 return false;
3881 if (!NewVal.isInt()) {
3882 // Maybe trying to write a cast pointer value into a complex?
3883 Info.FFDiag(E);
3884 return false;
3885 }
3886 Value = NewVal.getInt();
3887 return true;
3888 }
3889 bool found(APFloat &Value, QualType SubobjType) {
3890 if (!checkConst(SubobjType))
3891 return false;
3892 Value = NewVal.getFloat();
3893 return true;
3894 }
3895};
3896} // end anonymous namespace
3897
3898const AccessKinds ModifySubobjectHandler::AccessKind;
3899
3900/// Update the designated sub-object of an rvalue to the given value.
3901static bool modifySubobject(EvalInfo &Info, const Expr *E,
3902 const CompleteObject &Obj,
3903 const SubobjectDesignator &Sub,
3904 APValue &NewVal) {
3905 ModifySubobjectHandler Handler = { Info, NewVal, E };
3906 return findSubobject(Info, E, Obj, Sub, Handler);
3907}
3908
3909/// Find the position where two subobject designators diverge, or equivalently
3910/// the length of the common initial subsequence.
3911static unsigned FindDesignatorMismatch(QualType ObjType,
3912 const SubobjectDesignator &A,
3913 const SubobjectDesignator &B,
3914 bool &WasArrayIndex) {
3915 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3916 for (/**/; I != N; ++I) {
3917 if (!ObjType.isNull() &&
3918 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3919 // Next subobject is an array element.
3920 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3921 WasArrayIndex = true;
3922 return I;
3923 }
3924 if (ObjType->isAnyComplexType())
3925 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3926 else
3927 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3928 } else {
3929 if (A.Entries[I].getAsBaseOrMember() !=
3930 B.Entries[I].getAsBaseOrMember()) {
3931 WasArrayIndex = false;
3932 return I;
3933 }
3934 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3935 // Next subobject is a field.
3936 ObjType = FD->getType();
3937 else
3938 // Next subobject is a base class.
3939 ObjType = QualType();
3940 }
3941 }
3942 WasArrayIndex = false;
3943 return I;
3944}
3945
3946/// Determine whether the given subobject designators refer to elements of the
3947/// same array object.
3948static bool AreElementsOfSameArray(QualType ObjType,
3949 const SubobjectDesignator &A,
3950 const SubobjectDesignator &B) {
3951 if (A.Entries.size() != B.Entries.size())
3952 return false;
3953
3954 bool IsArray = A.MostDerivedIsArrayElement;
3955 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3956 // A is a subobject of the array element.
3957 return false;
3958
3959 // If A (and B) designates an array element, the last entry will be the array
3960 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3961 // of length 1' case, and the entire path must match.
3962 bool WasArrayIndex;
3963 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3964 return CommonLength >= A.Entries.size() - IsArray;
3965}
3966
3967/// Find the complete object to which an LValue refers.
3968static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3969 AccessKinds AK, const LValue &LVal,
3970 QualType LValType) {
3971 if (LVal.InvalidBase) {
3972 Info.FFDiag(E);
3973 return CompleteObject();
3974 }
3975
3976 if (!LVal.Base) {
3977 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3978 return CompleteObject();
3979 }
3980
3981 CallStackFrame *Frame = nullptr;
3982 unsigned Depth = 0;
3983 if (LVal.getLValueCallIndex()) {
3984 std::tie(Frame, Depth) =
3985 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3986 if (!Frame) {
3987 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3988 << AK << LVal.Base.is<const ValueDecl*>();
3989 NoteLValueLocation(Info, LVal.Base);
3990 return CompleteObject();
3991 }
3992 }
3993
3994 bool IsAccess = isAnyAccess(AK);
3995
3996 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3997 // is not a constant expression (even if the object is non-volatile). We also
3998 // apply this rule to C++98, in order to conform to the expected 'volatile'
3999 // semantics.
4000 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4001 if (Info.getLangOpts().CPlusPlus)
4002 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4003 << AK << LValType;
4004 else
4005 Info.FFDiag(E);
4006 return CompleteObject();
4007 }
4008
4009 // Compute value storage location and type of base object.
4010 APValue *BaseVal = nullptr;
4011 QualType BaseType = getType(LVal.Base);
4012
4013 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4014 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4015 // This is the object whose initializer we're evaluating, so its lifetime
4016 // started in the current evaluation.
4017 BaseVal = Info.EvaluatingDeclValue;
4018 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4019 // Allow reading from a GUID declaration.
4020 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4021 if (isModification(AK)) {
4022 // All the remaining cases do not permit modification of the object.
4023 Info.FFDiag(E, diag::note_constexpr_modify_global);
4024 return CompleteObject();
4025 }
4026 APValue &V = GD->getAsAPValue();
4027 if (V.isAbsent()) {
4028 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4029 << GD->getType();
4030 return CompleteObject();
4031 }
4032 return CompleteObject(LVal.Base, &V, GD->getType());
4033 }
4034
4035 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4036 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4037 if (isModification(AK)) {
4038 Info.FFDiag(E, diag::note_constexpr_modify_global);
4039 return CompleteObject();
4040 }
4041 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4042 GCD->getType());
4043 }
4044
4045 // Allow reading from template parameter objects.
4046 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4047 if (isModification(AK)) {
4048 Info.FFDiag(E, diag::note_constexpr_modify_global);
4049 return CompleteObject();
4050 }
4051 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4052 TPO->getType());
4053 }
4054
4055 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4056 // In C++11, constexpr, non-volatile variables initialized with constant
4057 // expressions are constant expressions too. Inside constexpr functions,
4058 // parameters are constant expressions even if they're non-const.
4059 // In C++1y, objects local to a constant expression (those with a Frame) are
4060 // both readable and writable inside constant expressions.
4061 // In C, such things can also be folded, although they are not ICEs.
4062 const VarDecl *VD = dyn_cast<VarDecl>(D);
4063 if (VD) {
4064 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4065 VD = VDef;
4066 }
4067 if (!VD || VD->isInvalidDecl()) {
4068 Info.FFDiag(E);
4069 return CompleteObject();
4070 }
4071
4072 bool IsConstant = BaseType.isConstant(Info.Ctx);
4073
4074 // Unless we're looking at a local variable or argument in a constexpr call,
4075 // the variable we're reading must be const.
4076 if (!Frame) {
4077 if (IsAccess && isa<ParmVarDecl>(VD)) {
4078 // Access of a parameter that's not associated with a frame isn't going
4079 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4080 // suitable diagnostic.
4081 } else if (Info.getLangOpts().CPlusPlus14 &&
4082 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4083 // OK, we can read and modify an object if we're in the process of
4084 // evaluating its initializer, because its lifetime began in this
4085 // evaluation.
4086 } else if (isModification(AK)) {
4087 // All the remaining cases do not permit modification of the object.
4088 Info.FFDiag(E, diag::note_constexpr_modify_global);
4089 return CompleteObject();
4090 } else if (VD->isConstexpr()) {
4091 // OK, we can read this variable.
4092 } else if (BaseType->isIntegralOrEnumerationType()) {
4093 if (!IsConstant) {
4094 if (!IsAccess)
4095 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4096 if (Info.getLangOpts().CPlusPlus) {
4097 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4098 Info.Note(VD->getLocation(), diag::note_declared_at);
4099 } else {
4100 Info.FFDiag(E);
4101 }
4102 return CompleteObject();
4103 }
4104 } else if (!IsAccess) {
4105 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4106 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4107 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4108 // This variable might end up being constexpr. Don't diagnose it yet.
4109 } else if (IsConstant) {
4110 // Keep evaluating to see what we can do. In particular, we support
4111 // folding of const floating-point types, in order to make static const
4112 // data members of such types (supported as an extension) more useful.
4113 if (Info.getLangOpts().CPlusPlus) {
4114 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4115 ? diag::note_constexpr_ltor_non_constexpr
4116 : diag::note_constexpr_ltor_non_integral, 1)
4117 << VD << BaseType;
4118 Info.Note(VD->getLocation(), diag::note_declared_at);
4119 } else {
4120 Info.CCEDiag(E);
4121 }
4122 } else {
4123 // Never allow reading a non-const value.
4124 if (Info.getLangOpts().CPlusPlus) {
4125 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4126 ? diag::note_constexpr_ltor_non_constexpr
4127 : diag::note_constexpr_ltor_non_integral, 1)
4128 << VD << BaseType;
4129 Info.Note(VD->getLocation(), diag::note_declared_at);
4130 } else {
4131 Info.FFDiag(E);
4132 }
4133 return CompleteObject();
4134 }
4135 }
4136
4137 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4138 return CompleteObject();
4139 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4140 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4141 if (!Alloc) {
4142 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4143 return CompleteObject();
4144 }
4145 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4146 LVal.Base.getDynamicAllocType());
4147 } else {
4148 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4149
4150 if (!Frame) {
4151 if (const MaterializeTemporaryExpr *MTE =
4152 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4153 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", 4154, __extension__ __PRETTY_FUNCTION__
))
4154 "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", 4154, __extension__ __PRETTY_FUNCTION__
))
;
4155
4156 // C++20 [expr.const]p4: [DR2126]
4157 // An object or reference is usable in constant expressions if it is
4158 // - a temporary object of non-volatile const-qualified literal type
4159 // whose lifetime is extended to that of a variable that is usable
4160 // in constant expressions
4161 //
4162 // C++20 [expr.const]p5:
4163 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4164 // - a non-volatile glvalue that refers to an object that is usable
4165 // in constant expressions, or
4166 // - a non-volatile glvalue of literal type that refers to a
4167 // non-volatile object whose lifetime began within the evaluation
4168 // of E;
4169 //
4170 // C++11 misses the 'began within the evaluation of e' check and
4171 // instead allows all temporaries, including things like:
4172 // int &&r = 1;
4173 // int x = ++r;
4174 // constexpr int k = r;
4175 // Therefore we use the C++14-onwards rules in C++11 too.
4176 //
4177 // Note that temporaries whose lifetimes began while evaluating a
4178 // variable's constructor are not usable while evaluating the
4179 // corresponding destructor, not even if they're of const-qualified
4180 // types.
4181 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4182 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4183 if (!IsAccess)
4184 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4185 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4186 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4187 return CompleteObject();
4188 }
4189
4190 BaseVal = MTE->getOrCreateValue(false);
4191 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", 4191, __extension__ __PRETTY_FUNCTION__
))
;
4192 } else {
4193 if (!IsAccess)
4194 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4195 APValue Val;
4196 LVal.moveInto(Val);
4197 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4198 << AK
4199 << Val.getAsString(Info.Ctx,
4200 Info.Ctx.getLValueReferenceType(LValType));
4201 NoteLValueLocation(Info, LVal.Base);
4202 return CompleteObject();
4203 }
4204 } else {
4205 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4206 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", 4206, __extension__ __PRETTY_FUNCTION__
))
;
4207 }
4208 }
4209
4210 // In C++14, we can't safely access any mutable state when we might be
4211 // evaluating after an unmodeled side effect. Parameters are modeled as state
4212 // in the caller, but aren't visible once the call returns, so they can be
4213 // modified in a speculatively-evaluated call.
4214 //
4215 // FIXME: Not all local state is mutable. Allow local constant subobjects
4216 // to be read here (but take care with 'mutable' fields).
4217 unsigned VisibleDepth = Depth;
4218 if (llvm::isa_and_nonnull<ParmVarDecl>(
4219 LVal.Base.dyn_cast<const ValueDecl *>()))
4220 ++VisibleDepth;
4221 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4222 Info.EvalStatus.HasSideEffects) ||
4223 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4224 return CompleteObject();
4225
4226 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4227}
4228
4229/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4230/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4231/// glvalue referred to by an entity of reference type.
4232///
4233/// \param Info - Information about the ongoing evaluation.
4234/// \param Conv - The expression for which we are performing the conversion.
4235/// Used for diagnostics.
4236/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4237/// case of a non-class type).
4238/// \param LVal - The glvalue on which we are attempting to perform this action.
4239/// \param RVal - The produced value will be placed here.
4240/// \param WantObjectRepresentation - If true, we're looking for the object
4241/// representation rather than the value, and in particular,
4242/// there is no requirement that the result be fully initialized.
4243static bool
4244handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4245 const LValue &LVal, APValue &RVal,
4246 bool WantObjectRepresentation = false) {
4247 if (LVal.Designator.Invalid)
4248 return false;
4249
4250 // Check for special cases where there is no existing APValue to look at.
4251 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4252
4253 AccessKinds AK =
4254 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4255
4256 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4257 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4258 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4259 // initializer until now for such expressions. Such an expression can't be
4260 // an ICE in C, so this only matters for fold.
4261 if (Type.isVolatileQualified()) {
4262 Info.FFDiag(Conv);
4263 return false;
4264 }
4265
4266 APValue Lit;
4267 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4268 return false;
4269
4270 // According to GCC info page:
4271 //
4272 // 6.28 Compound Literals
4273 //
4274 // As an optimization, G++ sometimes gives array compound literals longer
4275 // lifetimes: when the array either appears outside a function or has a
4276 // const-qualified type. If foo and its initializer had elements of type
4277 // char *const rather than char *, or if foo were a global variable, the
4278 // array would have static storage duration. But it is probably safest
4279 // just to avoid the use of array compound literals in C++ code.
4280 //
4281 // Obey that rule by checking constness for converted array types.
4282
4283 QualType CLETy = CLE->getType();
4284 if (CLETy->isArrayType() && !Type->isArrayType()) {
4285 if (!CLETy.isConstant(Info.Ctx)) {
4286 Info.FFDiag(Conv);
4287 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4288 return false;
4289 }
4290 }
4291
4292 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4293 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4294 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4295 // Special-case character extraction so we don't have to construct an
4296 // APValue for the whole string.
4297 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", 4298, __extension__ __PRETTY_FUNCTION__
))
4298 "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", 4298, __extension__ __PRETTY_FUNCTION__
))
;
4299 if (LVal.Designator.Entries.empty()) {
4300 // Fail for now for LValue to RValue conversion of an array.
4301 // (This shouldn't show up in C/C++, but it could be triggered by a
4302 // weird EvaluateAsRValue call from a tool.)
4303 Info.FFDiag(Conv);
4304 return false;
4305 }
4306 if (LVal.Designator.isOnePastTheEnd()) {
4307 if (Info.getLangOpts().CPlusPlus11)
4308 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4309 else
4310 Info.FFDiag(Conv);
4311 return false;
4312 }
4313 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4314 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4315 return true;
4316 }
4317 }
4318
4319 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4320 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4321}
4322
4323/// Perform an assignment of Val to LVal. Takes ownership of Val.
4324static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4325 QualType LValType, APValue &Val) {
4326 if (LVal.Designator.Invalid)
4327 return false;
4328
4329 if (!Info.getLangOpts().CPlusPlus14) {
4330 Info.FFDiag(E);
4331 return false;
4332 }
4333
4334 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4335 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4336}
4337
4338namespace {
4339struct CompoundAssignSubobjectHandler {
4340 EvalInfo &Info;
4341 const CompoundAssignOperator *E;
4342 QualType PromotedLHSType;
4343 BinaryOperatorKind Opcode;
4344 const APValue &RHS;
4345
4346 static const AccessKinds AccessKind = AK_Assign;
4347
4348 typedef bool result_type;
4349
4350 bool checkConst(QualType QT) {
4351 // Assigning to a const object has undefined behavior.
4352 if (QT.isConstQualified()) {
4353 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4354 return false;
4355 }
4356 return true;
4357 }
4358
4359 bool failed() { return false; }
4360 bool found(APValue &Subobj, QualType SubobjType) {
4361 switch (Subobj.getKind()) {
4362 case APValue::Int:
4363 return found(Subobj.getInt(), SubobjType);
4364 case APValue::Float:
4365 return found(Subobj.getFloat(), SubobjType);
4366 case APValue::ComplexInt:
4367 case APValue::ComplexFloat:
4368 // FIXME: Implement complex compound assignment.
4369 Info.FFDiag(E);
4370 return false;
4371 case APValue::LValue:
4372 return foundPointer(Subobj, SubobjType);
4373 case APValue::Vector:
4374 return foundVector(Subobj, SubobjType);
4375 default:
4376 // FIXME: can this happen?
4377 Info.FFDiag(E);
4378 return false;
4379 }
4380 }
4381
4382 bool foundVector(APValue &Value, QualType SubobjType) {
4383 if (!checkConst(SubobjType))
4384 return false;
4385
4386 if (!SubobjType->isVectorType()) {
4387 Info.FFDiag(E);
4388 return false;
4389 }
4390 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4391 }
4392
4393 bool found(APSInt &Value, QualType SubobjType) {
4394 if (!checkConst(SubobjType))
4395 return false;
4396
4397 if (!SubobjType->isIntegerType()) {
4398 // We don't support compound assignment on integer-cast-to-pointer
4399 // values.
4400 Info.FFDiag(E);
4401 return false;
4402 }
4403
4404 if (RHS.isInt()) {
4405 APSInt LHS =
4406 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4407 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4408 return false;
4409 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4410 return true;
4411 } else if (RHS.isFloat()) {
4412 const FPOptions FPO = E->getFPFeaturesInEffect(
4413 Info.Ctx.getLangOpts());
4414 APFloat FValue(0.0);
4415 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4416 PromotedLHSType, FValue) &&
4417 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4418 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4419 Value);
4420 }
4421
4422 Info.FFDiag(E);
4423 return false;
4424 }
4425 bool found(APFloat &Value, QualType SubobjType) {
4426 return checkConst(SubobjType) &&
4427 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4428 Value) &&
4429 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4430 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4431 }
4432 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4433 if (!checkConst(SubobjType))
4434 return false;
4435
4436 QualType PointeeType;
4437 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4438 PointeeType = PT->getPointeeType();
4439
4440 if (PointeeType.isNull() || !RHS.isInt() ||
4441 (Opcode != BO_Add && Opcode != BO_Sub)) {
4442 Info.FFDiag(E);
4443 return false;
4444 }
4445
4446 APSInt Offset = RHS.getInt();
4447 if (Opcode == BO_Sub)
4448 negateAsSigned(Offset);
4449
4450 LValue LVal;
4451 LVal.setFrom(Info.Ctx, Subobj);
4452 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4453 return false;
4454 LVal.moveInto(Subobj);
4455 return true;
4456 }
4457};
4458} // end anonymous namespace
4459
4460const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4461
4462/// Perform a compound assignment of LVal <op>= RVal.
4463static bool handleCompoundAssignment(EvalInfo &Info,
4464 const CompoundAssignOperator *E,
4465 const LValue &LVal, QualType LValType,
4466 QualType PromotedLValType,
4467 BinaryOperatorKind Opcode,
4468 const APValue &RVal) {
4469 if (LVal.Designator.Invalid)
4470 return false;
4471
4472 if (!Info.getLangOpts().CPlusPlus14) {
4473 Info.FFDiag(E);
4474 return false;
4475 }
4476
4477 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4478 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4479 RVal };
4480 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4481}
4482
4483namespace {
4484struct IncDecSubobjectHandler {
4485 EvalInfo &Info;
4486 const UnaryOperator *E;
4487 AccessKinds AccessKind;
4488 APValue *Old;
4489
4490 typedef bool result_type;
4491
4492 bool checkConst(QualType QT) {
4493 // Assigning to a const object has undefined behavior.
4494 if (QT.isConstQualified()) {
4495 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4496 return false;
4497 }
4498 return true;
4499 }
4500
4501 bool failed() { return false; }
4502 bool found(APValue &Subobj, QualType SubobjType) {
4503 // Stash the old value. Also clear Old, so we don't clobber it later
4504 // if we're post-incrementing a complex.
4505 if (Old) {
4506 *Old = Subobj;
4507 Old = nullptr;
4508 }
4509
4510 switch (Subobj.getKind()) {
4511 case APValue::Int:
4512 return found(Subobj.getInt(), SubobjType);
4513 case APValue::Float:
4514 return found(Subobj.getFloat(), SubobjType);
4515 case APValue::ComplexInt:
4516 return found(Subobj.getComplexIntReal(),
4517 SubobjType->castAs<ComplexType>()->getElementType()
4518 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4519 case APValue::ComplexFloat:
4520 return found(Subobj.getComplexFloatReal(),
4521 SubobjType->castAs<ComplexType>()->getElementType()
4522 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4523 case APValue::LValue:
4524 return foundPointer(Subobj, SubobjType);
4525 default:
4526 // FIXME: can this happen?
4527 Info.FFDiag(E);
4528 return false;
4529 }
4530 }
4531 bool found(APSInt &Value, QualType SubobjType) {
4532 if (!checkConst(SubobjType))
4533 return false;
4534
4535 if (!SubobjType->isIntegerType()) {
4536 // We don't support increment / decrement on integer-cast-to-pointer
4537 // values.
4538 Info.FFDiag(E);
4539 return false;
4540 }
4541
4542 if (Old) *Old = APValue(Value);
4543
4544 // bool arithmetic promotes to int, and the conversion back to bool
4545 // doesn't reduce mod 2^n, so special-case it.
4546 if (SubobjType->isBooleanType()) {
4547 if (AccessKind == AK_Increment)
4548 Value = 1;
4549 else
4550 Value = !Value;
4551 return true;
4552 }
4553
4554 bool WasNegative = Value.isNegative();
4555 if (AccessKind == AK_Increment) {
4556 ++Value;
4557
4558 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4559 APSInt ActualValue(Value, /*IsUnsigned*/true);
4560 return HandleOverflow(Info, E, ActualValue, SubobjType);
4561 }
4562 } else {
4563 --Value;
4564
4565 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4566 unsigned BitWidth = Value.getBitWidth();
4567 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4568 ActualValue.setBit(BitWidth);
4569 return HandleOverflow(Info, E, ActualValue, SubobjType);
4570 }
4571 }
4572 return true;
4573 }
4574 bool found(APFloat &Value, QualType SubobjType) {
4575 if (!checkConst(SubobjType))
4576 return false;
4577
4578 if (Old) *Old = APValue(Value);
4579
4580 APFloat One(Value.getSemantics(), 1);
4581 if (AccessKind == AK_Increment)
4582 Value.add(One, APFloat::rmNearestTiesToEven);
4583 else
4584 Value.subtract(One, APFloat::rmNearestTiesToEven);
4585 return true;
4586 }
4587 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4588 if (!checkConst(SubobjType))
4589 return false;
4590
4591 QualType PointeeType;
4592 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4593 PointeeType = PT->getPointeeType();
4594 else {
4595 Info.FFDiag(E);
4596 return false;
4597 }
4598
4599 LValue LVal;
4600 LVal.setFrom(Info.Ctx, Subobj);
4601 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4602 AccessKind == AK_Increment ? 1 : -1))
4603 return false;
4604 LVal.moveInto(Subobj);
4605 return true;
4606 }
4607};
4608} // end anonymous namespace
4609
4610/// Perform an increment or decrement on LVal.
4611static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4612 QualType LValType, bool IsIncrement, APValue *Old) {
4613 if (LVal.Designator.Invalid)
4614 return false;
4615
4616 if (!Info.getLangOpts().CPlusPlus14) {
4617 Info.FFDiag(E);
4618 return false;
4619 }
4620
4621 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4622 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4623 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4624 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4625}
4626
4627/// Build an lvalue for the object argument of a member function call.
4628static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4629 LValue &This) {
4630 if (Object->getType()->isPointerType() && Object->isPRValue())
4631 return EvaluatePointer(Object, This, Info);
4632
4633 if (Object->isGLValue())
4634 return EvaluateLValue(Object, This, Info);
4635
4636 if (Object->getType()->isLiteralType(Info.Ctx))
4637 return EvaluateTemporary(Object, This, Info);
4638
4639 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4640 return false;
4641}
4642
4643/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4644/// lvalue referring to the result.
4645///
4646/// \param Info - Information about the ongoing evaluation.
4647/// \param LV - An lvalue referring to the base of the member pointer.
4648/// \param RHS - The member pointer expression.
4649/// \param IncludeMember - Specifies whether the member itself is included in
4650/// the resulting LValue subobject designator. This is not possible when
4651/// creating a bound member function.
4652/// \return The field or method declaration to which the member pointer refers,
4653/// or 0 if evaluation fails.
4654static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4655 QualType LVType,
4656 LValue &LV,
4657 const Expr *RHS,
4658 bool IncludeMember = true) {
4659 MemberPtr MemPtr;
4660 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4661 return nullptr;
4662
4663 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4664 // member value, the behavior is undefined.
4665 if (!MemPtr.getDecl()) {
4666 // FIXME: Specific diagnostic.
4667 Info.FFDiag(RHS);
4668 return nullptr;
4669 }
4670
4671 if (MemPtr.isDerivedMember()) {
4672 // This is a member of some derived class. Truncate LV appropriately.
4673 // The end of the derived-to-base path for the base object must match the
4674 // derived-to-base path for the member pointer.
4675 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4676 LV.Designator.Entries.size()) {
4677 Info.FFDiag(RHS);
4678 return nullptr;
4679 }
4680 unsigned PathLengthToMember =
4681 LV.Designator.Entries.size() - MemPtr.Path.size();
4682 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4683 const CXXRecordDecl *LVDecl = getAsBaseClass(
4684 LV.Designator.Entries[PathLengthToMember + I]);
4685 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4686 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4687 Info.FFDiag(RHS);
4688 return nullptr;
4689 }
4690 }
4691
4692 // Truncate the lvalue to the appropriate derived class.
4693 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4694 PathLengthToMember))
4695 return nullptr;
4696 } else if (!MemPtr.Path.empty()) {
4697 // Extend the LValue path with the member pointer's path.
4698 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4699 MemPtr.Path.size() + IncludeMember);
4700
4701 // Walk down to the appropriate base class.
4702 if (const PointerType *PT = LVType->getAs<PointerType>())
4703 LVType = PT->getPointeeType();
4704 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4705 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", 4705, __extension__ __PRETTY_FUNCTION__
))
;
4706 // The first class in the path is that of the lvalue.
4707 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4708 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4709 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4710 return nullptr;
4711 RD = Base;
4712 }
4713 // Finally cast to the class containing the member.
4714 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4715 MemPtr.getContainingRecord()))
4716 return nullptr;
4717 }
4718
4719 // Add the member. Note that we cannot build bound member functions here.
4720 if (IncludeMember) {
4721 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4722 if (!HandleLValueMember(Info, RHS, LV, FD))
4723 return nullptr;
4724 } else if (const IndirectFieldDecl *IFD =
4725 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4726 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4727 return nullptr;
4728 } else {
4729 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", 4729)
;
4730 }
4731 }
4732
4733 return MemPtr.getDecl();
4734}
4735
4736static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4737 const BinaryOperator *BO,
4738 LValue &LV,
4739 bool IncludeMember = true) {
4740 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", 4740, __extension__ __PRETTY_FUNCTION__
))
;
4741
4742 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4743 if (Info.noteFailure()) {
4744 MemberPtr MemPtr;
4745 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4746 }
4747 return nullptr;
4748 }
4749
4750 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4751 BO->getRHS(), IncludeMember);
4752}
4753
4754/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4755/// the provided lvalue, which currently refers to the base object.
4756static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4757 LValue &Result) {
4758 SubobjectDesignator &D = Result.Designator;
4759 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4760 return false;
4761
4762 QualType TargetQT = E->getType();
4763 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4764 TargetQT = PT->getPointeeType();
4765
4766 // Check this cast lands within the final derived-to-base subobject path.
4767 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4768 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4769 << D.MostDerivedType << TargetQT;
4770 return false;
4771 }
4772
4773 // Check the type of the final cast. We don't need to check the path,
4774 // since a cast can only be formed if the path is unique.
4775 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4776 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4777 const CXXRecordDecl *FinalType;
4778 if (NewEntriesSize == D.MostDerivedPathLength)
4779 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4780 else
4781 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4782 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4783 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4784 << D.MostDerivedType << TargetQT;
4785 return false;
4786 }
4787
4788 // Truncate the lvalue to the appropriate derived class.
4789 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4790}
4791
4792/// Get the value to use for a default-initialized object of type T.
4793/// Return false if it encounters something invalid.
4794static bool getDefaultInitValue(QualType T, APValue &Result) {
4795 bool Success = true;
4796 if (auto *RD = T->getAsCXXRecordDecl()) {
4797 if (RD->isInvalidDecl()) {
4798 Result = APValue();
4799 return false;
4800 }
4801 if (RD->isUnion()) {
4802 Result = APValue((const FieldDecl *)nullptr);
4803 return true;
4804 }
4805 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4806 std::distance(RD->field_begin(), RD->field_end()));
4807
4808 unsigned Index = 0;
4809 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4810 End = RD->bases_end();
4811 I != End; ++I, ++Index)
4812 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4813
4814 for (const auto *I : RD->fields()) {
4815 if (I->isUnnamedBitfield())
4816 continue;
4817 Success &= getDefaultInitValue(I->getType(),
4818 Result.getStructField(I->getFieldIndex()));
4819 }
4820 return Success;
4821 }
4822
4823 if (auto *AT =
4824 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4825 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4826 if (Result.hasArrayFiller())
4827 Success &=
4828 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4829
4830 return Success;
4831 }
4832
4833 Result = APValue::IndeterminateValue();
4834 return true;
4835}
4836
4837namespace {
4838enum EvalStmtResult {
4839 /// Evaluation failed.
4840 ESR_Failed,
4841 /// Hit a 'return' statement.
4842 ESR_Returned,
4843 /// Evaluation succeeded.
4844 ESR_Succeeded,
4845 /// Hit a 'continue' statement.
4846 ESR_Continue,
4847 /// Hit a 'break' statement.
4848 ESR_Break,
4849 /// Still scanning for 'case' or 'default' statement.
4850 ESR_CaseNotFound
4851};
4852}
4853
4854static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4855 if (VD->isInvalidDecl())
4856 return false;
4857 // We don't need to evaluate the initializer for a static local.
4858 if (!VD->hasLocalStorage())
4859 return true;
4860
4861 LValue Result;
4862 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4863 ScopeKind::Block, Result);
4864
4865 const Expr *InitE = VD->getInit();
4866 if (!InitE) {
4867 if (VD->getType()->isDependentType())
4868 return Info.noteSideEffect();
4869 return getDefaultInitValue(VD->getType(), Val);
4870 }
4871 if (InitE->isValueDependent())
4872 return false;
4873
4874 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4875 // Wipe out any partially-computed value, to allow tracking that this
4876 // evaluation failed.
4877 Val = APValue();
4878 return false;
4879 }
4880
4881 return true;
4882}
4883
4884static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4885 bool OK = true;
4886
4887 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4888 OK &= EvaluateVarDecl(Info, VD);
4889
4890 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4891 for (auto *BD : DD->bindings())
4892 if (auto *VD = BD->getHoldingVar())
4893 OK &= EvaluateDecl(Info, VD);
4894
4895 return OK;
4896}
4897
4898static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4899 assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void (
0) : __assert_fail ("E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 4899, __extension__ __PRETTY_FUNCTION__))
;
4900 if (Info.noteSideEffect())
4901 return true;
4902 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", 4903, __extension__ __PRETTY_FUNCTION__
))
4903 "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", 4903, __extension__ __PRETTY_FUNCTION__
))
;
4904 return false;
4905}
4906
4907/// Evaluate a condition (either a variable declaration or an expression).
4908static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4909 const Expr *Cond, bool &Result) {
4910 if (Cond->isValueDependent())
4911 return false;
4912 FullExpressionRAII Scope(Info);
4913 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4914 return false;
4915 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4916 return false;
4917 return Scope.destroy();
4918}
4919
4920namespace {
4921/// A location where the result (returned value) of evaluating a
4922/// statement should be stored.
4923struct StmtResult {
4924 /// The APValue that should be filled in with the returned value.
4925 APValue &Value;
4926 /// The location containing the result, if any (used to support RVO).
4927 const LValue *Slot;
4928};
4929
4930struct TempVersionRAII {
4931 CallStackFrame &Frame;
4932
4933 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4934 Frame.pushTempVersion();
4935 }
4936
4937 ~TempVersionRAII() {
4938 Frame.popTempVersion();
4939 }
4940};
4941
4942}
4943
4944static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4945 const Stmt *S,
4946 const SwitchCase *SC = nullptr);
4947
4948/// Evaluate the body of a loop, and translate the result as appropriate.
4949static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4950 const Stmt *Body,
4951 const SwitchCase *Case = nullptr) {
4952 BlockScopeRAII Scope(Info);
4953
4954 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4955 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4956 ESR = ESR_Failed;
4957
4958 switch (ESR) {
4959 case ESR_Break:
4960 return ESR_Succeeded;
4961 case ESR_Succeeded:
4962 case ESR_Continue:
4963 return ESR_Continue;
4964 case ESR_Failed:
4965 case ESR_Returned:
4966 case ESR_CaseNotFound:
4967 return ESR;
4968 }
4969 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 4969)
;
4970}
4971
4972/// Evaluate a switch statement.
4973static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4974 const SwitchStmt *SS) {
4975 BlockScopeRAII Scope(Info);
4976
4977 // Evaluate the switch condition.
4978 APSInt Value;
4979 {
4980 if (const Stmt *Init = SS->getInit()) {
4981 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4982 if (ESR != ESR_Succeeded) {
4983 if (ESR != ESR_Failed && !Scope.destroy())
4984 ESR = ESR_Failed;
4985 return ESR;
4986 }
4987 }
4988
4989 FullExpressionRAII CondScope(Info);
4990 if (SS->getConditionVariable() &&
4991 !EvaluateDecl(Info, SS->getConditionVariable()))
4992 return ESR_Failed;
4993 if (SS->getCond()->isValueDependent()) {
4994 if (!EvaluateDependentExpr(SS->getCond(), Info))
4995 return ESR_Failed;
4996 } else {
4997 if (!EvaluateInteger(SS->getCond(), Value, Info))
4998 return ESR_Failed;
4999 }
5000 if (!CondScope.destroy())
5001 return ESR_Failed;
5002 }
5003
5004 // Find the switch case corresponding to the value of the condition.
5005 // FIXME: Cache this lookup.
5006 const SwitchCase *Found = nullptr;
5007 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5008 SC = SC->getNextSwitchCase()) {
5009 if (isa<DefaultStmt>(SC)) {
5010 Found = SC;
5011 continue;
5012 }
5013
5014 const CaseStmt *CS = cast<CaseStmt>(SC);
5015 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5016 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5017 : LHS;
5018 if (LHS <= Value && Value <= RHS) {
5019 Found = SC;
5020 break;
5021 }
5022 }
5023
5024 if (!Found)
5025 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5026
5027 // Search the switch body for the switch case and evaluate it from there.
5028 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5029 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5030 return ESR_Failed;
5031
5032 switch (ESR) {
5033 case ESR_Break:
5034 return ESR_Succeeded;
5035 case ESR_Succeeded:
5036 case ESR_Continue:
5037 case ESR_Failed:
5038 case ESR_Returned:
5039 return ESR;
5040 case ESR_CaseNotFound:
5041 // This can only happen if the switch case is nested within a statement
5042 // expression. We have no intention of supporting that.
5043 Info.FFDiag(Found->getBeginLoc(),
5044 diag::note_constexpr_stmt_expr_unsupported);
5045 return ESR_Failed;
5046 }
5047 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 5047)
;
5048}
5049
5050static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5051 // An expression E is a core constant expression unless the evaluation of E
5052 // would evaluate one of the following: [C++2b] - a control flow that passes
5053 // through a declaration of a variable with static or thread storage duration
5054 // unless that variable is usable in constant expressions.
5055 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5056 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5057 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5058 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5059 return false;
5060 }
5061 return true;
5062}
5063
5064// Evaluate a statement.
5065static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5066 const Stmt *S, const SwitchCase *Case) {
5067 if (!Info.nextStep(S))
5068 return ESR_Failed;
5069
5070 // If we're hunting down a 'case' or 'default' label, recurse through
5071 // substatements until we hit the label.
5072 if (Case) {
5073 switch (S->getStmtClass()) {
5074 case Stmt::CompoundStmtClass:
5075 // FIXME: Precompute which substatement of a compound statement we
5076 // would jump to, and go straight there rather than performing a
5077 // linear scan each time.
5078 case Stmt::LabelStmtClass:
5079 case Stmt::AttributedStmtClass:
5080 case Stmt::DoStmtClass:
5081 break;
5082
5083 case Stmt::CaseStmtClass:
5084 case Stmt::DefaultStmtClass:
5085 if (Case == S)
5086 Case = nullptr;
5087 break;
5088
5089 case Stmt::IfStmtClass: {
5090 // FIXME: Precompute which side of an 'if' we would jump to, and go
5091 // straight there rather than scanning both sides.
5092 const IfStmt *IS = cast<IfStmt>(S);
5093
5094 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5095 // preceded by our switch label.
5096 BlockScopeRAII Scope(Info);
5097
5098 // Step into the init statement in case it brings an (uninitialized)
5099 // variable into scope.
5100 if (const Stmt *Init = IS->getInit()) {
5101 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5102 if (ESR != ESR_CaseNotFound) {
5103 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5103, __extension__ __PRETTY_FUNCTION__))
;
5104 return ESR;
5105 }
5106 }
5107
5108 // Condition variable must be initialized if it exists.
5109 // FIXME: We can skip evaluating the body if there's a condition
5110 // variable, as there can't be any case labels within it.
5111 // (The same is true for 'for' statements.)
5112
5113 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5114 if (ESR == ESR_Failed)
5115 return ESR;
5116 if (ESR != ESR_CaseNotFound)
5117 return Scope.destroy() ? ESR : ESR_Failed;
5118 if (!IS->getElse())
5119 return ESR_CaseNotFound;
5120
5121 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5122 if (ESR == ESR_Failed)
5123 return ESR;
5124 if (ESR != ESR_CaseNotFound)
5125 return Scope.destroy() ? ESR : ESR_Failed;
5126 return ESR_CaseNotFound;
5127 }
5128
5129 case Stmt::WhileStmtClass: {
5130 EvalStmtResult ESR =
5131 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5132 if (ESR != ESR_Continue)
5133 return ESR;
5134 break;
5135 }
5136
5137 case Stmt::ForStmtClass: {
5138 const ForStmt *FS = cast<ForStmt>(S);
5139 BlockScopeRAII Scope(Info);
5140
5141 // Step into the init statement in case it brings an (uninitialized)
5142 // variable into scope.
5143 if (const Stmt *Init = FS->getInit()) {
5144 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5145 if (ESR != ESR_CaseNotFound) {
5146 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5146, __extension__ __PRETTY_FUNCTION__))
;
5147 return ESR;
5148 }
5149 }
5150
5151 EvalStmtResult ESR =
5152 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5153 if (ESR != ESR_Continue)
5154 return ESR;
5155 if (const auto *Inc = FS->getInc()) {
5156 if (Inc->isValueDependent()) {
5157 if (!EvaluateDependentExpr(Inc, Info))
5158 return ESR_Failed;
5159 } else {
5160 FullExpressionRAII IncScope(Info);
5161 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5162 return ESR_Failed;
5163 }
5164 }
5165 break;
5166 }
5167
5168 case Stmt::DeclStmtClass: {
5169 // Start the lifetime of any uninitialized variables we encounter. They
5170 // might be used by the selected branch of the switch.
5171 const DeclStmt *DS = cast<DeclStmt>(S);
5172 for (const auto *D : DS->decls()) {
5173 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5174 if (!CheckLocalVariableDeclaration(Info, VD))
5175 return ESR_Failed;
5176 if (VD->hasLocalStorage() && !VD->getInit())
5177 if (!EvaluateVarDecl(Info, VD))
5178 return ESR_Failed;
5179 // FIXME: If the variable has initialization that can't be jumped
5180 // over, bail out of any immediately-surrounding compound-statement
5181 // too. There can't be any case labels here.
5182 }
5183 }
5184 return ESR_CaseNotFound;
5185 }
5186
5187 default:
5188 return ESR_CaseNotFound;
5189 }
5190 }
5191
5192 switch (S->getStmtClass()) {
5193 default:
5194 if (const Expr *E = dyn_cast<Expr>(S)) {
5195 if (E->isValueDependent()) {
5196 if (!EvaluateDependentExpr(E, Info))
5197 return ESR_Failed;
5198 } else {
5199 // Don't bother evaluating beyond an expression-statement which couldn't
5200 // be evaluated.
5201 // FIXME: Do we need the FullExpressionRAII object here?
5202 // VisitExprWithCleanups should create one when necessary.
5203 FullExpressionRAII Scope(Info);
5204 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5205 return ESR_Failed;
5206 }
5207 return ESR_Succeeded;
5208 }
5209
5210 Info.FFDiag(S->getBeginLoc());
5211 return ESR_Failed;
5212
5213 case Stmt::NullStmtClass:
5214 return ESR_Succeeded;
5215
5216 case Stmt::DeclStmtClass: {
5217 const DeclStmt *DS = cast<DeclStmt>(S);
5218 for (const auto *D : DS->decls()) {
5219 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5220 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5221 return ESR_Failed;
5222 // Each declaration initialization is its own full-expression.
5223 FullExpressionRAII Scope(Info);
5224 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5225 return ESR_Failed;
5226 if (!Scope.destroy())
5227 return ESR_Failed;
5228 }
5229 return ESR_Succeeded;
5230 }
5231
5232 case Stmt::ReturnStmtClass: {
5233 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5234 FullExpressionRAII Scope(Info);
5235 if (RetExpr && RetExpr->isValueDependent()) {
5236 EvaluateDependentExpr(RetExpr, Info);
5237 // We know we returned, but we don't know what the value is.
5238 return ESR_Failed;
5239 }
5240 if (RetExpr &&
5241 !(Result.Slot
5242 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5243 : Evaluate(Result.Value, Info, RetExpr)))
5244 return ESR_Failed;
5245 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5246 }
5247
5248 case Stmt::CompoundStmtClass: {
5249 BlockScopeRAII Scope(Info);
5250
5251 const CompoundStmt *CS = cast<CompoundStmt>(S);
5252 for (const auto *BI : CS->body()) {
5253 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5254 if (ESR == ESR_Succeeded)
5255 Case = nullptr;
5256 else if (ESR != ESR_CaseNotFound) {
5257 if (ESR != ESR_Failed && !Scope.destroy())
5258 return ESR_Failed;
5259 return ESR;
5260 }
5261 }
5262 if (Case)
5263 return ESR_CaseNotFound;
5264 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5265 }
5266
5267 case Stmt::IfStmtClass: {
5268 const IfStmt *IS = cast<IfStmt>(S);
5269
5270 // Evaluate the condition, as either a var decl or as an expression.
5271 BlockScopeRAII Scope(Info);
5272 if (const Stmt *Init = IS->getInit()) {
5273 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5274 if (ESR != ESR_Succeeded) {
5275 if (ESR != ESR_Failed && !Scope.destroy())
5276 return ESR_Failed;
5277 return ESR;
5278 }
5279 }
5280 bool Cond;
5281 if (IS->isConsteval()) {
5282 Cond = IS->isNonNegatedConsteval();
5283 // If we are not in a constant context, if consteval should not evaluate
5284 // to true.
5285 if (!Info.InConstantContext)
5286 Cond = !Cond;
5287 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5288 Cond))
5289 return ESR_Failed;
5290
5291 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5292 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5293 if (ESR != ESR_Succeeded) {
5294 if (ESR != ESR_Failed && !Scope.destroy())
5295 return ESR_Failed;
5296 return ESR;
5297 }
5298 }
5299 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5300 }
5301
5302 case Stmt::WhileStmtClass: {
5303 const WhileStmt *WS = cast<WhileStmt>(S);
5304 while (true) {
5305 BlockScopeRAII Scope(Info);
5306 bool Continue;
5307 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5308 Continue))
5309 return ESR_Failed;
5310 if (!Continue)
5311 break;
5312
5313 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5314 if (ESR != ESR_Continue) {
5315 if (ESR != ESR_Failed && !Scope.destroy())
5316 return ESR_Failed;
5317 return ESR;
5318 }
5319 if (!Scope.destroy())
5320 return ESR_Failed;
5321 }
5322 return ESR_Succeeded;
5323 }
5324
5325 case Stmt::DoStmtClass: {
5326 const DoStmt *DS = cast<DoStmt>(S);
5327 bool Continue;
5328 do {
5329 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5330 if (ESR != ESR_Continue)
5331 return ESR;
5332 Case = nullptr;
5333
5334 if (DS->getCond()->isValueDependent()) {
5335 EvaluateDependentExpr(DS->getCond(), Info);
5336 // Bailout as we don't know whether to keep going or terminate the loop.
5337 return ESR_Failed;
5338 }
5339 FullExpressionRAII CondScope(Info);
5340 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5341 !CondScope.destroy())
5342 return ESR_Failed;
5343 } while (Continue);
5344 return ESR_Succeeded;
5345 }
5346
5347 case Stmt::ForStmtClass: {
5348 const ForStmt *FS = cast<ForStmt>(S);
5349 BlockScopeRAII ForScope(Info);
5350 if (FS->getInit()) {
5351 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5352 if (ESR != ESR_Succeeded) {
5353 if (ESR != ESR_Failed && !ForScope.destroy())
5354 return ESR_Failed;
5355 return ESR;
5356 }
5357 }
5358 while (true) {
5359 BlockScopeRAII IterScope(Info);
5360 bool Continue = true;
5361 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5362 FS->getCond(), Continue))
5363 return ESR_Failed;
5364 if (!Continue)
5365 break;
5366
5367 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5368 if (ESR != ESR_Continue) {
5369 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5370 return ESR_Failed;
5371 return ESR;
5372 }
5373
5374 if (const auto *Inc = FS->getInc()) {
5375 if (Inc->isValueDependent()) {
5376 if (!EvaluateDependentExpr(Inc, Info))
5377 return ESR_Failed;
5378 } else {
5379 FullExpressionRAII IncScope(Info);
5380 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5381 return ESR_Failed;
5382 }
5383 }
5384
5385 if (!IterScope.destroy())
5386 return ESR_Failed;
5387 }
5388 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5389 }
5390
5391 case Stmt::CXXForRangeStmtClass: {
5392 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5393 BlockScopeRAII Scope(Info);
5394
5395 // Evaluate the init-statement if present.
5396 if (FS->getInit()) {
5397 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5398 if (ESR != ESR_Succeeded) {
5399 if (ESR != ESR_Failed && !Scope.destroy())
5400 return ESR_Failed;
5401 return ESR;
5402 }
5403 }
5404
5405 // Initialize the __range variable.
5406 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5407 if (ESR != ESR_Succeeded) {
5408 if (ESR != ESR_Failed && !Scope.destroy())
5409 return ESR_Failed;
5410 return ESR;
5411 }
5412
5413 // In error-recovery cases it's possible to get here even if we failed to
5414 // synthesize the __begin and __end variables.
5415 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5416 return ESR_Failed;
5417
5418 // Create the __begin and __end iterators.
5419 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5420 if (ESR != ESR_Succeeded) {
5421 if (ESR != ESR_Failed && !Scope.destroy())
5422 return ESR_Failed;
5423 return ESR;
5424 }
5425 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5426 if (ESR != ESR_Succeeded) {
5427 if (ESR != ESR_Failed && !Scope.destroy())
5428 return ESR_Failed;
5429 return ESR;
5430 }
5431
5432 while (true) {
5433 // Condition: __begin != __end.
5434 {
5435 if (FS->getCond()->isValueDependent()) {
5436 EvaluateDependentExpr(FS->getCond(), Info);
5437 // We don't know whether to keep going or terminate the loop.
5438 return ESR_Failed;
5439 }
5440 bool Continue = true;
5441 FullExpressionRAII CondExpr(Info);
5442 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5443 return ESR_Failed;
5444 if (!Continue)
5445 break;
5446 }
5447
5448 // User's variable declaration, initialized by *__begin.
5449 BlockScopeRAII InnerScope(Info);
5450 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5451 if (ESR != ESR_Succeeded) {
5452 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5453 return ESR_Failed;
5454 return ESR;
5455 }
5456
5457 // Loop body.
5458 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5459 if (ESR != ESR_Continue) {
5460 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5461 return ESR_Failed;
5462 return ESR;
5463 }
5464 if (FS->getInc()->isValueDependent()) {
5465 if (!EvaluateDependentExpr(FS->getInc(), Info))
5466 return ESR_Failed;
5467 } else {
5468 // Increment: ++__begin
5469 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5470 return ESR_Failed;
5471 }
5472
5473 if (!InnerScope.destroy())
5474 return ESR_Failed;
5475 }
5476
5477 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5478 }
5479
5480 case Stmt::SwitchStmtClass:
5481 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5482
5483 case Stmt::ContinueStmtClass:
5484 return ESR_Continue;
5485
5486 case Stmt::BreakStmtClass:
5487 return ESR_Break;
5488
5489 case Stmt::LabelStmtClass:
5490 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5491
5492 case Stmt::AttributedStmtClass:
5493 // As a general principle, C++11 attributes can be ignored without
5494 // any semantic impact.
5495 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5496 Case);
5497
5498 case Stmt::CaseStmtClass:
5499 case Stmt::DefaultStmtClass:
5500 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5501 case Stmt::CXXTryStmtClass:
5502 // Evaluate try blocks by evaluating all sub statements.
5503 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5504 }
5505}
5506
5507/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5508/// default constructor. If so, we'll fold it whether or not it's marked as
5509/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5510/// so we need special handling.
5511static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5512 const CXXConstructorDecl *CD,
5513 bool IsValueInitialization) {
5514 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5515 return false;
5516
5517 // Value-initialization does not call a trivial default constructor, so such a
5518 // call is a core constant expression whether or not the constructor is
5519 // constexpr.
5520 if (!CD->isConstexpr() && !IsValueInitialization) {
5521 if (Info.getLangOpts().CPlusPlus11) {
5522 // FIXME: If DiagDecl is an implicitly-declared special member function,
5523 // we should be much more explicit about why it's not constexpr.
5524 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5525 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5526 Info.Note(CD->getLocation(), diag::note_declared_at);
5527 } else {
5528 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5529 }
5530 }
5531 return true;
5532}
5533
5534/// CheckConstexprFunction - Check that a function can be called in a constant
5535/// expression.
5536static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5537 const FunctionDecl *Declaration,
5538 const FunctionDecl *Definition,
5539 const Stmt *Body) {
5540 // Potential constant expressions can contain calls to declared, but not yet
5541 // defined, constexpr functions.
5542 if (Info.checkingPotentialConstantExpression() && !Definition &&
5543 Declaration->isConstexpr())
5544 return false;
5545
5546 // Bail out if the function declaration itself is invalid. We will
5547 // have produced a relevant diagnostic while parsing it, so just
5548 // note the problematic sub-expression.
5549 if (Declaration->isInvalidDecl()) {
5550 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5551 return false;
5552 }
5553
5554 // DR1872: An instantiated virtual constexpr function can't be called in a
5555 // constant expression (prior to C++20). We can still constant-fold such a
5556 // call.
5557 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5558 cast<CXXMethodDecl>(Declaration)->isVirtual())
5559 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5560
5561 if (Definition && Definition->isInvalidDecl()) {
5562 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5563 return false;
5564 }
5565
5566 // Can we evaluate this function call?
5567 if (Definition && Definition->isConstexpr() && Body)
5568 return true;
5569
5570 if (Info.getLangOpts().CPlusPlus11) {
5571 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5572
5573 // If this function is not constexpr because it is an inherited
5574 // non-constexpr constructor, diagnose that directly.
5575 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5576 if (CD && CD->isInheritingConstructor()) {
5577 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5578 if (!Inherited->isConstexpr())
5579 DiagDecl = CD = Inherited;
5580 }
5581
5582 // FIXME: If DiagDecl is an implicitly-declared special member function
5583 // or an inheriting constructor, we should be much more explicit about why
5584 // it's not constexpr.
5585 if (CD && CD->isInheritingConstructor())
5586 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5587 << CD->getInheritedConstructor().getConstructor()->getParent();
5588 else
5589 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5590 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5591 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5592 } else {
5593 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5594 }
5595 return false;
5596}
5597
5598namespace {
5599struct CheckDynamicTypeHandler {
5600 AccessKinds AccessKind;
5601 typedef bool result_type;
5602 bool failed() { return false; }
5603 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5604 bool found(APSInt &Value, QualType SubobjType) { return true; }
5605 bool found(APFloat &Value, QualType SubobjType) { return true; }
5606};
5607} // end anonymous namespace
5608
5609/// Check that we can access the notional vptr of an object / determine its
5610/// dynamic type.
5611static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5612 AccessKinds AK, bool Polymorphic) {
5613 if (This.Designator.Invalid)
5614 return false;
5615
5616 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5617
5618 if (!Obj)
5619 return false;
5620
5621 if (!Obj.Value) {
5622 // The object is not usable in constant expressions, so we can't inspect
5623 // its value to see if it's in-lifetime or what the active union members
5624 // are. We can still check for a one-past-the-end lvalue.
5625 if (This.Designator.isOnePastTheEnd() ||
5626 This.Designator.isMostDerivedAnUnsizedArray()) {
5627 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5628 ? diag::note_constexpr_access_past_end
5629 : diag::note_constexpr_access_unsized_array)
5630 << AK;
5631 return false;
5632 } else if (Polymorphic) {
5633 // Conservatively refuse to perform a polymorphic operation if we would
5634 // not be able to read a notional 'vptr' value.
5635 APValue Val;
5636 This.moveInto(Val);
5637 QualType StarThisType =
5638 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5639 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5640 << AK << Val.getAsString(Info.Ctx, StarThisType);
5641 return false;
5642 }
5643 return true;
5644 }
5645
5646 CheckDynamicTypeHandler Handler{AK};
5647 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5648}
5649
5650/// Check that the pointee of the 'this' pointer in a member function call is
5651/// either within its lifetime or in its period of construction or destruction.
5652static bool
5653checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5654 const LValue &This,
5655 const CXXMethodDecl *NamedMember) {
5656 return checkDynamicType(
5657 Info, E, This,
5658 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5659}
5660
5661struct DynamicType {
5662 /// The dynamic class type of the object.
5663 const CXXRecordDecl *Type;
5664 /// The corresponding path length in the lvalue.
5665 unsigned PathLength;
5666};
5667
5668static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5669 unsigned PathLength) {
5670 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", 5671, __extension__ __PRETTY_FUNCTION__
))
5671 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", 5671, __extension__ __PRETTY_FUNCTION__
))
;
5672 return (PathLength == Designator.MostDerivedPathLength)
5673 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5674 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5675}
5676
5677/// Determine the dynamic type of an object.
5678static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5679 LValue &This, AccessKinds AK) {
5680 // If we don't have an lvalue denoting an object of class type, there is no
5681 // meaningful dynamic type. (We consider objects of non-class type to have no
5682 // dynamic type.)
5683 if (!checkDynamicType(Info, E, This, AK, true))
5684 return std::nullopt;
5685
5686 // Refuse to compute a dynamic type in the presence of virtual bases. This
5687 // shouldn't happen other than in constant-folding situations, since literal
5688 // types can't have virtual bases.
5689 //
5690 // Note that consumers of DynamicType assume that the type has no virtual
5691 // bases, and will need modifications if this restriction is relaxed.
5692 const CXXRecordDecl *Class =
5693 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5694 if (!Class || Class->getNumVBases()) {
5695 Info.FFDiag(E);
5696 return std::nullopt;
5697 }
5698
5699 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5700 // binary search here instead. But the overwhelmingly common case is that
5701 // we're not in the middle of a constructor, so it probably doesn't matter
5702 // in practice.
5703 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5704 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5705 PathLength <= Path.size(); ++PathLength) {
5706 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5707 Path.slice(0, PathLength))) {
5708 case ConstructionPhase::Bases:
5709 case ConstructionPhase::DestroyingBases:
5710 // We're constructing or destroying a base class. This is not the dynamic
5711 // type.
5712 break;
5713
5714 case ConstructionPhase::None:
5715 case ConstructionPhase::AfterBases:
5716 case ConstructionPhase::AfterFields:
5717 case ConstructionPhase::Destroying:
5718 // We've finished constructing the base classes and not yet started
5719 // destroying them again, so this is the dynamic type.
5720 return DynamicType{getBaseClassType(This.Designator, PathLength),
5721 PathLength};
5722 }
5723 }
5724
5725 // CWG issue 1517: we're constructing a base class of the object described by
5726 // 'This', so that object has not yet begun its period of construction and
5727 // any polymorphic operation on it results in undefined behavior.
5728 Info.FFDiag(E);
5729 return std::nullopt;
5730}
5731
5732/// Perform virtual dispatch.
5733static const CXXMethodDecl *HandleVirtualDispatch(
5734 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5735 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5736 Optional<DynamicType> DynType = ComputeDynamicType(
5737 Info, E, This,
5738 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5739 if (!DynType)
5740 return nullptr;
5741
5742 // Find the final overrider. It must be declared in one of the classes on the
5743 // path from the dynamic type to the static type.
5744 // FIXME: If we ever allow literal types to have virtual base classes, that
5745 // won't be true.
5746 const CXXMethodDecl *Callee = Found;
5747 unsigned PathLength = DynType->PathLength;
5748 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5749 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5750 const CXXMethodDecl *Overrider =
5751 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5752 if (Overrider) {
5753 Callee = Overrider;
5754 break;
5755 }
5756 }
5757
5758 // C++2a [class.abstract]p6:
5759 // the effect of making a virtual call to a pure virtual function [...] is
5760 // undefined
5761 if (Callee->isPure()) {
5762 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5763 Info.Note(Callee->getLocation(), diag::note_declared_at);
5764 return nullptr;
5765 }
5766
5767 // If necessary, walk the rest of the path to determine the sequence of
5768 // covariant adjustment steps to apply.
5769 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5770 Found->getReturnType())) {
5771 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5772 for (unsigned CovariantPathLength = PathLength + 1;
5773 CovariantPathLength != This.Designator.Entries.size();
5774 ++CovariantPathLength) {
5775 const CXXRecordDecl *NextClass =
5776 getBaseClassType(This.Designator, CovariantPathLength);
5777 const CXXMethodDecl *Next =
5778 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5779 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5780 Next->getReturnType(), CovariantAdjustmentPath.back()))
5781 CovariantAdjustmentPath.push_back(Next->getReturnType());
5782 }
5783 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5784 CovariantAdjustmentPath.back()))
5785 CovariantAdjustmentPath.push_back(Found->getReturnType());
5786 }
5787
5788 // Perform 'this' adjustment.
5789 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5790 return nullptr;
5791
5792 return Callee;
5793}
5794
5795/// Perform the adjustment from a value returned by a virtual function to
5796/// a value of the statically expected type, which may be a pointer or
5797/// reference to a base class of the returned type.
5798static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5799 APValue &Result,
5800 ArrayRef<QualType> Path) {
5801 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", 5802, __extension__ __PRETTY_FUNCTION__
))
5802 "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", 5802, __extension__ __PRETTY_FUNCTION__
))
;
5803 if (Result.isNullPointer())
5804 return true;
5805
5806 LValue LVal;
5807 LVal.setFrom(Info.Ctx, Result);
5808
5809 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5810 for (unsigned I = 1; I != Path.size(); ++I) {
5811 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5812 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", 5812, __extension__ __PRETTY_FUNCTION__
))
;
5813 if (OldClass != NewClass &&
5814 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5815 return false;
5816 OldClass = NewClass;
5817 }
5818
5819 LVal.moveInto(Result);
5820 return true;
5821}
5822
5823/// Determine whether \p Base, which is known to be a direct base class of
5824/// \p Derived, is a public base class.
5825static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5826 const CXXRecordDecl *Base) {
5827 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5828 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5829 if (BaseClass && declaresSameEntity(BaseClass, Base))
5830 return BaseSpec.getAccessSpecifier() == AS_public;
5831 }
5832 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", 5832)
;
5833}
5834
5835/// Apply the given dynamic cast operation on the provided lvalue.
5836///
5837/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5838/// to find a suitable target subobject.
5839static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5840 LValue &Ptr) {
5841 // We can't do anything with a non-symbolic pointer value.
5842 SubobjectDesignator &D = Ptr.Designator;
5843 if (D.Invalid)
5844 return false;
5845
5846 // C++ [expr.dynamic.cast]p6:
5847 // If v is a null pointer value, the result is a null pointer value.
5848 if (Ptr.isNullPointer() && !E->isGLValue())
5849 return true;
5850
5851 // For all the other cases, we need the pointer to point to an object within
5852 // its lifetime / period of construction / destruction, and we need to know
5853 // its dynamic type.
5854 Optional<DynamicType> DynType =
5855 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5856 if (!DynType)
5857 return false;
5858
5859 // C++ [expr.dynamic.cast]p7:
5860 // If T is "pointer to cv void", then the result is a pointer to the most
5861 // derived object
5862 if (E->getType()->isVoidPointerType())
5863 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5864
5865 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5866 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", 5866, __extension__ __PRETTY_FUNCTION__
))
;
5867 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5868
5869 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5870 // C++ [expr.dynamic.cast]p9:
5871 if (!E->isGLValue()) {
5872 // The value of a failed cast to pointer type is the null pointer value
5873 // of the required result type.
5874 Ptr.setNull(Info.Ctx, E->getType());
5875 return true;
5876 }
5877
5878 // A failed cast to reference type throws [...] std::bad_cast.
5879 unsigned DiagKind;
5880 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5881 DynType->Type->isDerivedFrom(C)))
5882 DiagKind = 0;
5883 else if (!Paths || Paths->begin() == Paths->end())
5884 DiagKind = 1;
5885 else if (Paths->isAmbiguous(CQT))
5886 DiagKind = 2;
5887 else {
5888 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", 5888, __extension__ __PRETTY_FUNCTION__
))
;
5889 DiagKind = 3;
5890 }
5891 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5892 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5893 << Info.Ctx.getRecordType(DynType->Type)
5894 << E->getType().getUnqualifiedType();
5895 return false;
5896 };
5897
5898 // Runtime check, phase 1:
5899 // Walk from the base subobject towards the derived object looking for the
5900 // target type.
5901 for (int PathLength = Ptr.Designator.Entries.size();
5902 PathLength >= (int)DynType->PathLength; --PathLength) {
5903 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5904 if (declaresSameEntity(Class, C))
5905 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5906 // We can only walk across public inheritance edges.
5907 if (PathLength > (int)DynType->PathLength &&
5908 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5909 Class))
5910 return RuntimeCheckFailed(nullptr);
5911 }
5912
5913 // Runtime check, phase 2:
5914 // Search the dynamic type for an unambiguous public base of type C.
5915 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5916 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5917 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5918 Paths.front().Access == AS_public) {
5919 // Downcast to the dynamic type...
5920 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5921 return false;
5922 // ... then upcast to the chosen base class subobject.
5923 for (CXXBasePathElement &Elem : Paths.front())
5924 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5925 return false;
5926 return true;
5927 }
5928
5929 // Otherwise, the runtime check fails.
5930 return RuntimeCheckFailed(&Paths);
5931}
5932
5933namespace {
5934struct StartLifetimeOfUnionMemberHandler {
5935 EvalInfo &Info;
5936 const Expr *LHSExpr;
5937 const FieldDecl *Field;
5938 bool DuringInit;
5939 bool Failed = false;
5940 static const AccessKinds AccessKind = AK_Assign;
5941
5942 typedef bool result_type;
5943 bool failed() { return Failed; }
5944 bool found(APValue &Subobj, QualType SubobjType) {
5945 // We are supposed to perform no initialization but begin the lifetime of
5946 // the object. We interpret that as meaning to do what default
5947 // initialization of the object would do if all constructors involved were
5948 // trivial:
5949 // * All base, non-variant member, and array element subobjects' lifetimes
5950 // begin
5951 // * No variant members' lifetimes begin
5952 // * All scalar subobjects whose lifetimes begin have indeterminate values
5953 assert(SubobjType->isUnionType())(static_cast <bool> (SubobjType->isUnionType()) ? void
(0) : __assert_fail ("SubobjType->isUnionType()", "clang/lib/AST/ExprConstant.cpp"
, 5953, __extension__ __PRETTY_FUNCTION__))
;
5954 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5955 // This union member is already active. If it's also in-lifetime, there's
5956 // nothing to do.
5957 if (Subobj.getUnionValue().hasValue())
5958 return true;
5959 } else if (DuringInit) {
5960 // We're currently in the process of initializing a different union
5961 // member. If we carried on, that initialization would attempt to
5962 // store to an inactive union member, resulting in undefined behavior.
5963 Info.FFDiag(LHSExpr,
5964 diag::note_constexpr_union_member_change_during_init);
5965 return false;
5966 }
5967 APValue Result;
5968 Failed = !getDefaultInitValue(Field->getType(), Result);
5969 Subobj.setUnion(Field, Result);
5970 return true;
5971 }
5972 bool found(APSInt &Value, QualType SubobjType) {
5973 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "clang/lib/AST/ExprConstant.cpp", 5973)
;
5974 }
5975 bool found(APFloat &Value, QualType SubobjType) {
5976 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "clang/lib/AST/ExprConstant.cpp", 5976)
;
5977 }
5978};
5979} // end anonymous namespace
5980
5981const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5982
5983/// Handle a builtin simple-assignment or a call to a trivial assignment
5984/// operator whose left-hand side might involve a union member access. If it
5985/// does, implicitly start the lifetime of any accessed union elements per
5986/// C++20 [class.union]5.
5987static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5988 const LValue &LHS) {
5989 if (LHS.InvalidBase || LHS.Designator.Invalid)
5990 return false;
5991
5992 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5993 // C++ [class.union]p5:
5994 // define the set S(E) of subexpressions of E as follows:
5995 unsigned PathLength = LHS.Designator.Entries.size();
5996 for (const Expr *E = LHSExpr; E != nullptr;) {
5997 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5998 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5999 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6000 // Note that we can't implicitly start the lifetime of a reference,
6001 // so we don't need to proceed any further if we reach one.
6002 if (!FD || FD->getType()->isReferenceType())
6003 break;
6004
6005 // ... and also contains A.B if B names a union member ...
6006 if (FD->getParent()->isUnion()) {
6007 // ... of a non-class, non-array type, or of a class type with a
6008 // trivial default constructor that is not deleted, or an array of
6009 // such types.
6010 auto *RD =
6011 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6012 if (!RD || RD->hasTrivialDefaultConstructor())
6013 UnionPathLengths.push_back({PathLength - 1, FD});
6014 }
6015
6016 E = ME->getBase();
6017 --PathLength;
6018 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", 6020, __extension__ __PRETTY_FUNCTION__
))
6019 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", 6020, __extension__ __PRETTY_FUNCTION__
))
6020 .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", 6020, __extension__ __PRETTY_FUNCTION__
))
;
6021
6022 // -- If E is of the form A[B] and is interpreted as a built-in array
6023 // subscripting operator, S(E) is [S(the array operand, if any)].
6024 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6025 // Step over an ArrayToPointerDecay implicit cast.
6026 auto *Base = ASE->getBase()->IgnoreImplicit();
6027 if (!Base->getType()->isArrayType())
6028 break;
6029
6030 E = Base;
6031 --PathLength;
6032
6033 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6034 // Step over a derived-to-base conversion.
6035 E = ICE->getSubExpr();
6036 if (ICE->getCastKind() == CK_NoOp)
6037 continue;
6038 if (ICE->getCastKind() != CK_DerivedToBase &&
6039 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6040 break;
6041 // Walk path backwards as we walk up from the base to the derived class.
6042 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6043 --PathLength;
6044 (void)Elt;
6045 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", 6047, __extension__ __PRETTY_FUNCTION__
))
6046 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", 6047, __extension__ __PRETTY_FUNCTION__
))
6047 .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", 6047, __extension__ __PRETTY_FUNCTION__
))
;
6048 }
6049
6050 // -- Otherwise, S(E) is empty.
6051 } else {
6052 break;
6053 }
6054 }
6055
6056 // Common case: no unions' lifetimes are started.
6057 if (UnionPathLengths.empty())
6058 return true;
6059
6060 // if modification of X [would access an inactive union member], an object
6061 // of the type of X is implicitly created
6062 CompleteObject Obj =
6063 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6064 if (!Obj)
6065 return false;
6066 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6067 llvm::reverse(UnionPathLengths)) {
6068 // Form a designator for the union object.
6069 SubobjectDesignator D = LHS.Designator;
6070 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6071
6072 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6073 ConstructionPhase::AfterBases;
6074 StartLifetimeOfUnionMemberHandler StartLifetime{
6075 Info, LHSExpr, LengthAndField.second, DuringInit};
6076 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6077 return false;
6078 }
6079
6080 return true;
6081}
6082
6083static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6084 CallRef Call, EvalInfo &Info,
6085 bool NonNull = false) {
6086 LValue LV;
6087 // Create the parameter slot and register its destruction. For a vararg
6088 // argument, create a temporary.
6089 // FIXME: For calling conventions that destroy parameters in the callee,
6090 // should we consider performing destruction when the function returns
6091 // instead?
6092 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6093 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6094 ScopeKind::Call, LV);
6095 if (!EvaluateInPlace(V, Info, LV, Arg))
6096 return false;
6097
6098 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6099 // undefined behavior, so is non-constant.
6100 if (NonNull && V.isLValue() && V.isNullPointer()) {
6101 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6102 return false;
6103 }
6104
6105 return true;
6106}
6107
6108/// Evaluate the arguments to a function call.
6109static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6110 EvalInfo &Info, const FunctionDecl *Callee,
6111 bool RightToLeft = false) {
6112 bool Success = true;
6113 llvm::SmallBitVector ForbiddenNullArgs;
6114 if (Callee->hasAttr<NonNullAttr>()) {
6115 ForbiddenNullArgs.resize(Args.size());
6116 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6117 if (!Attr->args_size()) {
6118 ForbiddenNullArgs.set();
6119 break;
6120 } else
6121 for (auto Idx : Attr->args()) {
6122 unsigned ASTIdx = Idx.getASTIndex();
6123 if (ASTIdx >= Args.size())
6124 continue;
6125 ForbiddenNullArgs[ASTIdx] = true;
6126 }
6127 }
6128 }
6129 for (unsigned I = 0; I < Args.size(); I++) {
6130 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6131 const ParmVarDecl *PVD =
6132 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6133 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6134 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6135 // If we're checking for a potential constant expression, evaluate all
6136 // initializers even if some of them fail.
6137 if (!Info.noteFailure())
6138 return false;
6139 Success = false;
6140 }
6141 }
6142 return Success;
6143}
6144
6145/// Perform a trivial copy from Param, which is the parameter of a copy or move
6146/// constructor or assignment operator.
6147static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6148 const Expr *E, APValue &Result,
6149 bool CopyObjectRepresentation) {
6150 // Find the reference argument.
6151 CallStackFrame *Frame = Info.CurrentCall;
6152 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6153 if (!RefValue) {
6154 Info.FFDiag(E);
6155 return false;
6156 }
6157
6158 // Copy out the contents of the RHS object.
6159 LValue RefLValue;
6160 RefLValue.setFrom(Info.Ctx, *RefValue);
6161 return handleLValueToRValueConversion(
6162 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6163 CopyObjectRepresentation);
6164}
6165
6166/// Evaluate a function call.
6167static bool HandleFunctionCall(SourceLocation CallLoc,
6168 const FunctionDecl *Callee, const LValue *This,
6169 ArrayRef<const Expr *> Args, CallRef Call,
6170 const Stmt *Body, EvalInfo &Info,
6171 APValue &Result, const LValue *ResultSlot) {
6172 if (!Info.CheckCallLimit(CallLoc))
6173 return false;
6174
6175 CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6176
6177 // For a trivial copy or move assignment, perform an APValue copy. This is
6178 // essential for unions, where the operations performed by the assignment
6179 // operator cannot be represented as statements.
6180 //
6181 // Skip this for non-union classes with no fields; in that case, the defaulted
6182 // copy/move does not actually read the object.
6183 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6184 if (MD && MD->isDefaulted() &&
6185 (MD->getParent()->isUnion() ||
6186 (MD->isTrivial() &&
6187 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6188 assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "clang/lib/AST/ExprConstant.cpp", 6189, __extension__ __PRETTY_FUNCTION__
))
6189 (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", 6189, __extension__ __PRETTY_FUNCTION__
))
;
6190 APValue RHSValue;
6191 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6192 MD->getParent()->isUnion()))
6193 return false;
6194 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6195 RHSValue))
6196 return false;
6197 This->moveInto(Result);
6198 return true;
6199 } else if (MD && isLambdaCallOperator(MD)) {
6200 // We're in a lambda; determine the lambda capture field maps unless we're
6201 // just constexpr checking a lambda's call operator. constexpr checking is
6202 // done before the captures have been added to the closure object (unless
6203 // we're inferring constexpr-ness), so we don't have access to them in this
6204 // case. But since we don't need the captures to constexpr check, we can
6205 // just ignore them.
6206 if (!Info.checkingPotentialConstantExpression())
6207 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6208 Frame.LambdaThisCaptureField);
6209 }
6210
6211 StmtResult Ret = {Result, ResultSlot};
6212 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6213 if (ESR == ESR_Succeeded) {
6214 if (Callee->getReturnType()->isVoidType())
6215 return true;
6216 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6217 }
6218 return ESR == ESR_Returned;
6219}
6220
6221/// Evaluate a constructor call.
6222static bool HandleConstructorCall(const Expr *E, const LValue &This,
6223 CallRef Call,
6224 const CXXConstructorDecl *Definition,
6225 EvalInfo &Info, APValue &Result) {
6226 SourceLocation CallLoc = E->getExprLoc();
6227 if (!Info.CheckCallLimit(CallLoc))
6228 return false;
6229
6230 const CXXRecordDecl *RD = Definition->getParent();
6231 if (RD->getNumVBases()) {
6232 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6233 return false;
6234 }
6235
6236 EvalInfo::EvaluatingConstructorRAII EvalObj(
6237 Info,
6238 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6239 RD->getNumBases());
6240 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6241
6242 // FIXME: Creating an APValue just to hold a nonexistent return value is
6243 // wasteful.
6244 APValue RetVal;
6245 StmtResult Ret = {RetVal, nullptr};
6246
6247 // If it's a delegating constructor, delegate.
6248 if (Definition->isDelegatingConstructor()) {
6249 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6250 if ((*I)->getInit()->isValueDependent()) {
6251 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6252 return false;
6253 } else {
6254 FullExpressionRAII InitScope(Info);
6255 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6256 !InitScope.destroy())
6257 return false;
6258 }
6259 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6260 }
6261
6262 // For a trivial copy or move constructor, perform an APValue copy. This is
6263 // essential for unions (or classes with anonymous union members), where the
6264 // operations performed by the constructor cannot be represented by
6265 // ctor-initializers.
6266 //
6267 // Skip this for empty non-union classes; we should not perform an
6268 // lvalue-to-rvalue conversion on them because their copy constructor does not
6269 // actually read them.
6270 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6271 (Definition->getParent()->isUnion() ||
6272 (Definition->isTrivial() &&
6273 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6274 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6275 Definition->getParent()->isUnion());
6276 }
6277
6278 // Reserve space for the struct members.
6279 if (!Result.hasValue()) {
6280 if (!RD->isUnion())
6281 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6282 std::distance(RD->field_begin(), RD->field_end()));
6283 else
6284 // A union starts with no active member.
6285 Result = APValue((const FieldDecl*)nullptr);
6286 }
6287
6288 if (RD->isInvalidDecl()) return false;
6289 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6290
6291 // A scope for temporaries lifetime-extended by reference members.
6292 BlockScopeRAII LifetimeExtendedScope(Info);
6293
6294 bool Success = true;
6295 unsigned BasesSeen = 0;
6296#ifndef NDEBUG
6297 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6298#endif
6299 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6300 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6301 // We might be initializing the same field again if this is an indirect
6302 // field initialization.
6303 if (FieldIt == RD->field_end() ||
6304 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6305 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", 6305, __extension__ __PRETTY_FUNCTION__
))
;
6306 return;
6307 }
6308
6309 // Default-initialize any fields with no explicit initializer.
6310 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6311 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", 6311, __extension__ __PRETTY_FUNCTION__
))
;
6312 if (!FieldIt->isUnnamedBitfield())
6313 Success &= getDefaultInitValue(
6314 FieldIt->getType(),
6315 Result.getStructField(FieldIt->getFieldIndex()));
6316 }
6317 ++FieldIt;
6318 };
6319 for (const auto *I : Definition->inits()) {
6320 LValue Subobject = This;
6321 LValue SubobjectParent = This;
6322 APValue *Value = &Result;
6323
6324 // Determine the subobject to initialize.
6325 FieldDecl *FD = nullptr;
6326 if (I->isBaseInitializer()) {
6327 QualType BaseType(I->getBaseClass(), 0);
6328#ifndef NDEBUG
6329 // Non-virtual base classes are initialized in the order in the class
6330 // definition. We have already checked for virtual base classes.
6331 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", 6331, __extension__ __PRETTY_FUNCTION__
))
;
6332 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", 6333, __extension__ __PRETTY_FUNCTION__
))
6333 "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", 6333, __extension__ __PRETTY_FUNCTION__
))
;
6334 ++BaseIt;
6335#endif
6336 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6337 BaseType->getAsCXXRecordDecl(), &Layout))
6338 return false;
6339 Value = &Result.getStructBase(BasesSeen++);
6340 } else if ((FD = I->getMember())) {
6341 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6342 return false;
6343 if (RD->isUnion()) {
6344 Result = APValue(FD);
6345 Value = &Result.getUnionValue();
6346 } else {
6347 SkipToField(FD, false);
6348 Value = &Result.getStructField(FD->getFieldIndex());
6349 }
6350 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6351 // Walk the indirect field decl's chain to find the object to initialize,
6352 // and make sure we've initialized every step along it.
6353 auto IndirectFieldChain = IFD->chain();
6354 for (auto *C : IndirectFieldChain) {
6355 FD = cast<FieldDecl>(C);
6356 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6357 // Switch the union field if it differs. This happens if we had
6358 // preceding zero-initialization, and we're now initializing a union
6359 // subobject other than the first.
6360 // FIXME: In this case, the values of the other subobjects are
6361 // specified, since zero-initialization sets all padding bits to zero.
6362 if (!Value->hasValue() ||
6363 (Value->isUnion() && Value->getUnionField() != FD)) {
6364 if (CD->isUnion())
6365 *Value = APValue(FD);
6366 else
6367 // FIXME: This immediately starts the lifetime of all members of
6368 // an anonymous struct. It would be preferable to strictly start
6369 // member lifetime in initialization order.
6370 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6371 }
6372 // Store Subobject as its parent before updating it for the last element
6373 // in the chain.
6374 if (C == IndirectFieldChain.back())
6375 SubobjectParent = Subobject;
6376 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6377 return false;
6378 if (CD->isUnion())
6379 Value = &Value->getUnionValue();
6380 else {
6381 if (C == IndirectFieldChain.front() && !RD->isUnion())
6382 SkipToField(FD, true);
6383 Value = &Value->getStructField(FD->getFieldIndex());
6384 }
6385 }
6386 } else {
6387 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "clang/lib/AST/ExprConstant.cpp", 6387)
;
6388 }
6389
6390 // Need to override This for implicit field initializers as in this case
6391 // This refers to innermost anonymous struct/union containing initializer,
6392 // not to currently constructed class.
6393 const Expr *Init = I->getInit();
6394 if (Init->isValueDependent()) {
6395 if (!EvaluateDependentExpr(Init, Info))
6396 return false;
6397 } else {
6398 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6399 isa<CXXDefaultInitExpr>(Init));
6400 FullExpressionRAII InitScope(Info);
6401 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6402 (FD && FD->isBitField() &&
6403 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6404 // If we're checking for a potential constant expression, evaluate all
6405 // initializers even if some of them fail.
6406 if (!Info.noteFailure())
6407 return false;
6408 Success = false;
6409 }
6410 }
6411
6412 // This is the point at which the dynamic type of the object becomes this
6413 // class type.
6414 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6415 EvalObj.finishedConstructingBases();
6416 }
6417
6418 // Default-initialize any remaining fields.
6419 if (!RD->isUnion()) {
6420 for (; FieldIt != RD->field_end(); ++FieldIt) {
6421 if (!FieldIt->isUnnamedBitfield())
6422 Success &= getDefaultInitValue(
6423 FieldIt->getType(),
6424 Result.getStructField(FieldIt->getFieldIndex()));
6425 }
6426 }
6427
6428 EvalObj.finishedConstructingFields();
6429
6430 return Success &&
6431 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6432 LifetimeExtendedScope.destroy();
6433}
6434
6435static bool HandleConstructorCall(const Expr *E, const LValue &This,
6436 ArrayRef<const Expr*> Args,
6437 const CXXConstructorDecl *Definition,
6438 EvalInfo &Info, APValue &Result) {
6439 CallScopeRAII CallScope(Info);
6440 CallRef Call = Info.CurrentCall->createCall(Definition);
6441 if (!EvaluateArgs(Args, Call, Info, Definition))
6442 return false;
6443
6444 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6445 CallScope.destroy();
6446}
6447
6448static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6449 const LValue &This, APValue &Value,
6450 QualType T) {
6451 // Objects can only be destroyed while they're within their lifetimes.
6452 // FIXME: We have no representation for whether an object of type nullptr_t
6453 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6454 // as indeterminate instead?
6455 if (Value.isAbsent() && !T->isNullPtrType()) {
6456 APValue Printable;
6457 This.moveInto(Printable);
6458 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6459 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6460 return false;
6461 }
6462
6463 // Invent an expression for location purposes.
6464 // FIXME: We shouldn't need to do this.
6465 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6466
6467 // For arrays, destroy elements right-to-left.
6468 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6469 uint64_t Size = CAT->getSize().getZExtValue();
6470 QualType ElemT = CAT->getElementType();
6471
6472 LValue ElemLV = This;
6473 ElemLV.addArray(Info, &LocE, CAT);
6474 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6475 return false;
6476
6477 // Ensure that we have actual array elements available to destroy; the
6478 // destructors might mutate the value, so we can't run them on the array
6479 // filler.
6480 if (Size && Size > Value.getArrayInitializedElts())
6481 expandArray(Value, Value.getArraySize() - 1);
6482
6483 for (; Size != 0; --Size) {
6484 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6485 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6486 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6487 return false;
6488 }
6489
6490 // End the lifetime of this array now.
6491 Value = APValue();
6492 return true;
6493 }
6494
6495 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6496 if (!RD) {
6497 if (T.isDestructedType()) {
6498 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6499 return false;
6500 }
6501
6502 Value = APValue();
6503 return true;
6504 }
6505
6506 if (RD->getNumVBases()) {
6507 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6508 return false;
6509 }
6510
6511 const CXXDestructorDecl *DD = RD->getDestructor();
6512 if (!DD && !RD->hasTrivialDestructor()) {
6513 Info.FFDiag(CallLoc);
6514 return false;
6515 }
6516
6517 if (!DD || DD->isTrivial() ||
6518 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6519 // A trivial destructor just ends the lifetime of the object. Check for
6520 // this case before checking for a body, because we might not bother
6521 // building a body for a trivial destructor. Note that it doesn't matter
6522 // whether the destructor is constexpr in this case; all trivial
6523 // destructors are constexpr.
6524 //
6525 // If an anonymous union would be destroyed, some enclosing destructor must
6526 // have been explicitly defined, and the anonymous union destruction should
6527 // have no effect.
6528 Value = APValue();
6529 return true;
6530 }
6531
6532 if (!Info.CheckCallLimit(CallLoc))
6533 return false;
6534
6535 const FunctionDecl *Definition = nullptr;
6536 const Stmt *Body = DD->getBody(Definition);
6537
6538 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6539 return false;
6540
6541 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6542
6543 // We're now in the period of destruction of this object.
6544 unsigned BasesLeft = RD->getNumBases();
6545 EvalInfo::EvaluatingDestructorRAII EvalObj(
6546 Info,
6547 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6548 if (!EvalObj.DidInsert) {
6549 // C++2a [class.dtor]p19:
6550 // the behavior is undefined if the destructor is invoked for an object
6551 // whose lifetime has ended
6552 // (Note that formally the lifetime ends when the period of destruction
6553 // begins, even though certain uses of the object remain valid until the
6554 // period of destruction ends.)
6555 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6556 return false;
6557 }
6558
6559 // FIXME: Creating an APValue just to hold a nonexistent return value is
6560 // wasteful.
6561 APValue RetVal;
6562 StmtResult Ret = {RetVal, nullptr};
6563 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6564 return false;
6565
6566 // A union destructor does not implicitly destroy its members.
6567 if (RD->isUnion())
6568 return true;
6569
6570 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6571
6572 // We don't have a good way to iterate fields in reverse, so collect all the
6573 // fields first and then walk them backwards.
6574 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6575 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6576 if (FD->isUnnamedBitfield())
6577 continue;
6578
6579 LValue Subobject = This;
6580 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6581 return false;
6582
6583 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6584 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6585 FD->getType()))
6586 return false;
6587 }
6588
6589 if (BasesLeft != 0)
6590 EvalObj.startedDestroyingBases();
6591
6592 // Destroy base classes in reverse order.
6593 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6594 --BasesLeft;
6595
6596 QualType BaseType = Base.getType();
6597 LValue Subobject = This;
6598 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6599 BaseType->getAsCXXRecordDecl(), &Layout))
6600 return false;
6601
6602 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6603 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6604 BaseType))
6605 return false;
6606 }
6607 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", 6607, __extension__ __PRETTY_FUNCTION__
))
;
6608
6609 // The period of destruction ends now. The object is gone.
6610 Value = APValue();
6611 return true;
6612}
6613
6614namespace {
6615struct DestroyObjectHandler {
6616 EvalInfo &Info;
6617 const Expr *E;
6618 const LValue &This;
6619 const AccessKinds AccessKind;
6620
6621 typedef bool result_type;
6622 bool failed() { return false; }
6623 bool found(APValue &Subobj, QualType SubobjType) {
6624 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6625 SubobjType);
6626 }
6627 bool found(APSInt &Value, QualType SubobjType) {
6628 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6629 return false;
6630 }
6631 bool found(APFloat &Value, QualType SubobjType) {
6632 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6633 return false;
6634 }
6635};
6636}
6637
6638/// Perform a destructor or pseudo-destructor call on the given object, which
6639/// might in general not be a complete object.
6640static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6641 const LValue &This, QualType ThisType) {
6642 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6643 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6644 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6645}
6646
6647/// Destroy and end the lifetime of the given complete object.
6648static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6649 APValue::LValueBase LVBase, APValue &Value,
6650 QualType T) {
6651 // If we've had an unmodeled side-effect, we can't rely on mutable state
6652 // (such as the object we're about to destroy) being correct.
6653 if (Info.EvalStatus.HasSideEffects)
6654 return false;
6655
6656 LValue LV;
6657 LV.set({LVBase});
6658 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6659}
6660
6661/// Perform a call to 'perator new' or to `__builtin_operator_new'.
6662static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6663 LValue &Result) {
6664 if (Info.checkingPotentialConstantExpression() ||
6665 Info.SpeculativeEvaluationDepth)
6666 return false;
6667
6668 // This is permitted only within a call to std::allocator<T>::allocate.
6669 auto Caller = Info.getStdAllocatorCaller("allocate");
6670 if (!Caller) {
6671 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6672 ? diag::note_constexpr_new_untyped
6673 : diag::note_constexpr_new);
6674 return false;
6675 }
6676
6677 QualType ElemType = Caller.ElemType;
6678 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6679 Info.FFDiag(E->getExprLoc(),
6680 diag::note_constexpr_new_not_complete_object_type)
6681 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6682 return false;
6683 }
6684
6685 APSInt ByteSize;
6686 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6687 return false;
6688 bool IsNothrow = false;
6689 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6690 EvaluateIgnoredValue(Info, E->getArg(I));
6691 IsNothrow |= E->getType()->isNothrowT();
6692 }
6693
6694 CharUnits ElemSize;
6695 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6696 return false;
6697 APInt Size, Remainder;
6698 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6699 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6700 if (Remainder != 0) {
6701 // This likely indicates a bug in the implementation of 'std::allocator'.
6702 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6703 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6704 return false;
6705 }
6706
6707 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6708 if (IsNothrow) {
6709 Result.setNull(Info.Ctx, E->getType());
6710 return true;
6711 }
6712
6713 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6714 return false;
6715 }
6716
6717 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6718 ArrayType::Normal, 0);
6719 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6720 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6721 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6722 return true;
6723}
6724
6725static bool hasVirtualDestructor(QualType T) {
6726 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6727 if (CXXDestructorDecl *DD = RD->getDestructor())
6728 return DD->isVirtual();
6729 return false;
6730}
6731
6732static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6733 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6734 if (CXXDestructorDecl *DD = RD->getDestructor())
6735 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6736 return nullptr;
6737}
6738
6739/// Check that the given object is a suitable pointer to a heap allocation that
6740/// still exists and is of the right kind for the purpose of a deletion.
6741///
6742/// On success, returns the heap allocation to deallocate. On failure, produces
6743/// a diagnostic and returns std::nullopt.
6744static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6745 const LValue &Pointer,
6746 DynAlloc::Kind DeallocKind) {
6747 auto PointerAsString = [&] {
6748 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6749 };
6750
6751 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6752 if (!DA) {
6753 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6754 << PointerAsString();
6755 if (Pointer.Base)
6756 NoteLValueLocation(Info, Pointer.Base);
6757 return std::nullopt;
6758 }
6759
6760 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6761 if (!Alloc) {
6762 Info.FFDiag(E, diag::note_constexpr_double_delete);
6763 return std::nullopt;
6764 }
6765
6766 QualType AllocType = Pointer.Base.getDynamicAllocType();
6767 if (DeallocKind != (*Alloc)->getKind()) {
6768 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6769 << DeallocKind << (*Alloc)->getKind() << AllocType;
6770 NoteLValueLocation(Info, Pointer.Base);
6771 return std::nullopt;
6772 }
6773
6774 bool Subobject = false;
6775 if (DeallocKind == DynAlloc::New) {
6776 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6777 Pointer.Designator.isOnePastTheEnd();
6778 } else {
6779 Subobject = Pointer.Designator.Entries.size() != 1 ||
6780 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6781 }
6782 if (Subobject) {
6783 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6784 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6785 return std::nullopt;
6786 }
6787
6788 return Alloc;
6789}
6790
6791// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6792bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6793 if (Info.checkingPotentialConstantExpression() ||
6794 Info.SpeculativeEvaluationDepth)
6795 return false;
6796
6797 // This is permitted only within a call to std::allocator<T>::deallocate.
6798 if (!Info.getStdAllocatorCaller("deallocate")) {
6799 Info.FFDiag(E->getExprLoc());
6800 return true;
6801 }
6802
6803 LValue Pointer;
6804 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6805 return false;
6806 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6807 EvaluateIgnoredValue(Info, E->getArg(I));
6808
6809 if (Pointer.Designator.Invalid)
6810 return false;
6811
6812 // Deleting a null pointer would have no effect, but it's not permitted by
6813 // std::allocator<T>::deallocate's contract.
6814 if (Pointer.isNullPointer()) {
6815 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6816 return true;
6817 }
6818
6819 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6820 return false;
6821
6822 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6823 return true;
6824}
6825
6826//===----------------------------------------------------------------------===//
6827// Generic Evaluation
6828//===----------------------------------------------------------------------===//
6829namespace {
6830
6831class BitCastBuffer {
6832 // FIXME: We're going to need bit-level granularity when we support
6833 // bit-fields.
6834 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6835 // we don't support a host or target where that is the case. Still, we should
6836 // use a more generic type in case we ever do.
6837 SmallVector<std::optional<unsigned char>, 32> Bytes;
6838
6839 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6840 "Need at least 8 bit unsigned char");
6841
6842 bool TargetIsLittleEndian;
6843
6844public:
6845 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6846 : Bytes(Width.getQuantity()),
6847 TargetIsLittleEndian(TargetIsLittleEndian) {}
6848
6849 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6850 SmallVectorImpl<unsigned char> &Output) const {
6851 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6852 // If a byte of an integer is uninitialized, then the whole integer is
6853 // uninitialized.
6854 if (!Bytes[I.getQuantity()])
6855 return false;
6856 Output.push_back(*Bytes[I.getQuantity()]);
6857 }
6858 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6859 std::reverse(Output.begin(), Output.end());
6860 return true;
6861 }
6862
6863 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6864 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6865 std::reverse(Input.begin(), Input.end());
6866
6867 size_t Index = 0;
6868 for (unsigned char Byte : Input) {
6869 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", 6869, __extension__ __PRETTY_FUNCTION__
))
;
6870 Bytes[Offset.getQuantity() + Index] = Byte;
6871 ++Index;
6872 }
6873 }
6874
6875 size_t size() { return Bytes.size(); }
6876};
6877
6878/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6879/// target would represent the value at runtime.
6880class APValueToBufferConverter {
6881 EvalInfo &Info;
6882 BitCastBuffer Buffer;
6883 const CastExpr *BCE;
6884
6885 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6886 const CastExpr *BCE)
6887 : Info(Info),
6888 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6889 BCE(BCE) {}
6890
6891 bool visit(const APValue &Val, QualType Ty) {
6892 return visit(Val, Ty, CharUnits::fromQuantity(0));
6893 }
6894
6895 // Write out Val with type Ty into Buffer starting at Offset.
6896 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6897 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", 6897, __extension__ __PRETTY_FUNCTION__
))
;
6898
6899 // As a special case, nullptr_t has an indeterminate value.
6900 if (Ty->isNullPtrType())
6901 return true;
6902
6903 // Dig through Src to find the byte at SrcOffset.
6904 switch (Val.getKind()) {
6905 case APValue::Indeterminate:
6906 case APValue::None:
6907 return true;
6908
6909 case APValue::Int:
6910 return visitInt(Val.getInt(), Ty, Offset);
6911 case APValue::Float:
6912 return visitFloat(Val.getFloat(), Ty, Offset);
6913 case APValue::Array:
6914 return visitArray(Val, Ty, Offset);
6915 case APValue::Struct:
6916 return visitRecord(Val, Ty, Offset);
6917
6918 case APValue::ComplexInt:
6919 case APValue::ComplexFloat:
6920 case APValue::Vector:
6921 case APValue::FixedPoint:
6922 // FIXME: We should support these.
6923
6924 case APValue::Union:
6925 case APValue::MemberPointer:
6926 case APValue::AddrLabelDiff: {
6927 Info.FFDiag(BCE->getBeginLoc(),
6928 diag::note_constexpr_bit_cast_unsupported_type)
6929 << Ty;
6930 return false;
6931 }
6932
6933 case APValue::LValue:
6934 llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?"
, "clang/lib/AST/ExprConstant.cpp", 6934)
;
6935 }
6936 llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind"
, "clang/lib/AST/ExprConstant.cpp", 6936)
;
6937 }
6938
6939 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6940 const RecordDecl *RD = Ty->getAsRecordDecl();
6941 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6942
6943 // Visit the base classes.
6944 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6945 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6946 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6947 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6948
6949 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6950 Layout.getBaseClassOffset(BaseDecl) + Offset))
6951 return false;
6952 }
6953 }
6954
6955 // Visit the fields.
6956 unsigned FieldIdx = 0;
6957 for (FieldDecl *FD : RD->fields()) {
6958 if (FD->isBitField()) {
6959 Info.FFDiag(BCE->getBeginLoc(),
6960 diag::note_constexpr_bit_cast_unsupported_bitfield);
6961 return false;
6962 }
6963
6964 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6965
6966 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", 6967, __extension__ __PRETTY_FUNCTION__
))
6967 "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", 6967, __extension__ __PRETTY_FUNCTION__
))
;
6968 CharUnits FieldOffset =
6969 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6970 QualType FieldTy = FD->getType();
6971 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6972 return false;
6973 ++FieldIdx;
6974 }
6975
6976 return true;
6977 }
6978
6979 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6980 const auto *CAT =
6981 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6982 if (!CAT)
6983 return false;
6984
6985 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6986 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6987 unsigned ArraySize = Val.getArraySize();
6988 // First, initialize the initialized elements.
6989 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6990 const APValue &SubObj = Val.getArrayInitializedElt(I);
6991 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6992 return false;
6993 }
6994
6995 // Next, initialize the rest of the array using the filler.
6996 if (Val.hasArrayFiller()) {
6997 const APValue &Filler = Val.getArrayFiller();
6998 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6999 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7000 return false;
7001 }
7002 }
7003
7004 return true;
7005 }
7006
7007 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7008 APSInt AdjustedVal = Val;
7009 unsigned Width = AdjustedVal.getBitWidth();
7010 if (Ty->isBooleanType()) {
7011 Width = Info.Ctx.getTypeSize(Ty);
7012 AdjustedVal = AdjustedVal.extend(Width);
7013 }
7014
7015 SmallVector<unsigned char, 8> Bytes(Width / 8);
7016 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7017 Buffer.writeObject(Offset, Bytes);
7018 return true;
7019 }
7020
7021 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7022 APSInt AsInt(Val.bitcastToAPInt());
7023 return visitInt(AsInt, Ty, Offset);
7024 }
7025
7026public:
7027 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7028 const CastExpr *BCE) {
7029 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7030 APValueToBufferConverter Converter(Info, DstSize, BCE);
7031 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7032 return std::nullopt;
7033 return Converter.Buffer;
7034 }
7035};
7036
7037/// Write an BitCastBuffer into an APValue.
7038class BufferToAPValueConverter {
7039 EvalInfo &Info;
7040 const BitCastBuffer &Buffer;
7041 const CastExpr *BCE;
7042
7043 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7044 const CastExpr *BCE)
7045 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7046
7047 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7048 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7049 // Ideally this will be unreachable.
7050 std::nullopt_t unsupportedType(QualType Ty) {
7051 Info.FFDiag(BCE->getBeginLoc(),
7052 diag::note_constexpr_bit_cast_unsupported_type)
7053 << Ty;
7054 return std::nullopt;
7055 }
7056
7057 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7058 Info.FFDiag(BCE->getBeginLoc(),
7059 diag::note_constexpr_bit_cast_unrepresentable_value)
7060 << Ty << toString(Val, /*Radix=*/10);
7061 return std::nullopt;
7062 }
7063
7064 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7065 const EnumType *EnumSugar = nullptr) {
7066 if (T->isNullPtrType()) {
7067 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7068 return APValue((Expr *)nullptr,
7069 /*Offset=*/CharUnits::fromQuantity(NullValue),
7070 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7071 }
7072
7073 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7074
7075 // Work around floating point types that contain unused padding bytes. This
7076 // is really just `long double` on x86, which is the only fundamental type
7077 // with padding bytes.
7078 if (T->isRealFloatingType()) {
7079 const llvm::fltSemantics &Semantics =
7080 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7081 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7082 assert(NumBits % 8 == 0)(static_cast <bool> (NumBits % 8 == 0) ? void (0) : __assert_fail
("NumBits % 8 == 0", "clang/lib/AST/ExprConstant.cpp", 7082,
__extension__ __PRETTY_FUNCTION__))
;
7083 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7084 if (NumBytes != SizeOf)
7085 SizeOf = NumBytes;
7086 }
7087
7088 SmallVector<uint8_t, 8> Bytes;
7089 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7090 // If this is std::byte or unsigned char, then its okay to store an
7091 // indeterminate value.
7092 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7093 bool IsUChar =
7094 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7095 T->isSpecificBuiltinType(BuiltinType::Char_U));
7096 if (!IsStdByte && !IsUChar) {
7097 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7098 Info.FFDiag(BCE->getExprLoc(),
7099 diag::note_constexpr_bit_cast_indet_dest)
7100 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7101 return std::nullopt;
7102 }
7103
7104 return APValue::IndeterminateValue();
7105 }
7106
7107 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7108 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7109
7110 if (T->isIntegralOrEnumerationType()) {
7111 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7112
7113 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7114 if (IntWidth != Val.getBitWidth()) {
7115 APSInt Truncated = Val.trunc(IntWidth);
7116 if (Truncated.extend(Val.getBitWidth()) != Val)
7117 return unrepresentableValue(QualType(T, 0), Val);
7118 Val = Truncated;
7119 }
7120
7121 return APValue(Val);
7122 }
7123
7124 if (T->isRealFloatingType()) {
7125 const llvm::fltSemantics &Semantics =
7126 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7127 return APValue(APFloat(Semantics, Val));
7128 }
7129
7130 return unsupportedType(QualType(T, 0));
7131 }
7132
7133 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7134 const RecordDecl *RD = RTy->getAsRecordDecl();
7135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7136
7137 unsigned NumBases = 0;
7138 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7139 NumBases = CXXRD->getNumBases();
7140
7141 APValue ResultVal(APValue::UninitStruct(), NumBases,
7142 std::distance(RD->field_begin(), RD->field_end()));
7143
7144 // Visit the base classes.
7145 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7146 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7147 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7148 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7149 if (BaseDecl->isEmpty() ||
7150 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7151 continue;
7152
7153 Optional<APValue> SubObj = visitType(
7154 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7155 if (!SubObj)
7156 return std::nullopt;
7157 ResultVal.getStructBase(I) = *SubObj;
7158 }
7159 }
7160
7161 // Visit the fields.
7162 unsigned FieldIdx = 0;
7163 for (FieldDecl *FD : RD->fields()) {
7164 // FIXME: We don't currently support bit-fields. A lot of the logic for
7165 // this is in CodeGen, so we need to factor it around.
7166 if (FD->isBitField()) {
7167 Info.FFDiag(BCE->getBeginLoc(),
7168 diag::note_constexpr_bit_cast_unsupported_bitfield);
7169 return std::nullopt;
7170 }
7171
7172 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7173 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", 7173, __extension__ __PRETTY_FUNCTION__
))
;
7174
7175 CharUnits FieldOffset =
7176 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7177 Offset;
7178 QualType FieldTy = FD->getType();
7179 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7180 if (!SubObj)
7181 return std::nullopt;
7182 ResultVal.getStructField(FieldIdx) = *SubObj;
7183 ++FieldIdx;
7184 }
7185
7186 return ResultVal;
7187 }
7188
7189 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7190 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7191 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", 7192, __extension__ __PRETTY_FUNCTION__
))
7192 "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", 7192, __extension__ __PRETTY_FUNCTION__
))
;
7193 const auto *AsBuiltin =
7194 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7195 // Recurse into the underlying type. Treat std::byte transparently as
7196 // unsigned char.
7197 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7198 }
7199
7200 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7201 size_t Size = Ty->getSize().getLimitedValue();
7202 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7203
7204 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7205 for (size_t I = 0; I != Size; ++I) {
7206 Optional<APValue> ElementValue =
7207 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7208 if (!ElementValue)
7209 return std::nullopt;
7210 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7211 }
7212
7213 return ArrayValue;
7214 }
7215
7216 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7217 return unsupportedType(QualType(Ty, 0));
7218 }
7219
7220 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7221 QualType Can = Ty.getCanonicalType();
7222
7223 switch (Can->getTypeClass()) {
7224#define TYPE(Class, Base) \
7225 case Type::Class: \
7226 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7227#define ABSTRACT_TYPE(Class, Base)
7228#define NON_CANONICAL_TYPE(Class, Base) \
7229 case Type::Class: \
7230 llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!"
, "clang/lib/AST/ExprConstant.cpp", 7230)
;
7231#define DEPENDENT_TYPE(Class, Base) \
7232 case Type::Class: \
7233 llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!"
, "clang/lib/AST/ExprConstant.cpp", 7234)
7234 "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", 7234)
;
7235#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "clang/lib/AST/ExprConstant.cpp", 7235);
\
7236 case Type::Class: \
7237 llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "clang/lib/AST/ExprConstant.cpp", 7237)
;
7238#include "clang/AST/TypeNodes.inc"
7239 }
7240 llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass"
, "clang/lib/AST/ExprConstant.cpp", 7240)
;
7241 }
7242
7243public:
7244 // Pull out a full value of type DstType.
7245 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7246 const CastExpr *BCE) {
7247 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7248 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7249 }
7250};
7251
7252static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7253 QualType Ty, EvalInfo *Info,
7254 const ASTContext &Ctx,
7255 bool CheckingDest) {
7256 Ty = Ty.getCanonicalType();
7257
7258 auto diag = [&](int Reason) {
7259 if (Info)
7260 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7261 << CheckingDest << (Reason == 4) << Reason;
7262 return false;
7263 };
7264 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7265 if (Info)
7266 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7267 << NoteTy << Construct << Ty;
7268 return false;
7269 };
7270
7271 if (Ty->isUnionType())
7272 return diag(0);
7273 if (Ty->isPointerType())
7274 return diag(1);
7275 if (Ty->isMemberPointerType())
7276 return diag(2);
7277 if (Ty.isVolatileQualified())
7278 return diag(3);
7279
7280 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7281 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7282 for (CXXBaseSpecifier &BS : CXXRD->bases())
7283 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7284 CheckingDest))
7285 return note(1, BS.getType(), BS.getBeginLoc());
7286 }
7287 for (FieldDecl *FD : Record->fields()) {
7288 if (FD->getType()->isReferenceType())
7289 return diag(4);
7290 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7291 CheckingDest))
7292 return note(0, FD->getType(), FD->getBeginLoc());
7293 }
7294 }
7295
7296 if (Ty->isArrayType() &&
7297 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7298 Info, Ctx, CheckingDest))
7299 return false;
7300
7301 return true;
7302}
7303
7304static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7305 const ASTContext &Ctx,
7306 const CastExpr *BCE) {
7307 bool DestOK = checkBitCastConstexprEligibilityType(
7308 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7309 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7310 BCE->getBeginLoc(),
7311 BCE->getSubExpr()->getType(), Info, Ctx, false);
7312 return SourceOK;
7313}
7314
7315static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7316 APValue &SourceValue,
7317 const CastExpr *BCE) {
7318 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", 7319, __extension__ __PRETTY_FUNCTION__
))
7319 "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", 7319, __extension__ __PRETTY_FUNCTION__
))
;
7320 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", 7321, __extension__ __PRETTY_FUNCTION__
))
7321 "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", 7321, __extension__ __PRETTY_FUNCTION__
))
;
7322
7323 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7324 return false;
7325
7326 LValue SourceLValue;
7327 APValue SourceRValue;
7328 SourceLValue.setFrom(Info.Ctx, SourceValue);
7329 if (!handleLValueToRValueConversion(
7330 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7331 SourceRValue, /*WantObjectRepresentation=*/true))
7332 return false;
7333
7334 // Read out SourceValue into a char buffer.
7335 Optional<BitCastBuffer> Buffer =
7336 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7337 if (!Buffer)
7338 return false;
7339
7340 // Write out the buffer into a new APValue.
7341 Optional<APValue> MaybeDestValue =
7342 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7343 if (!MaybeDestValue)
7344 return false;
7345
7346 DestValue = std::move(*MaybeDestValue);
7347 return true;
7348}
7349
7350template <class Derived>
7351class ExprEvaluatorBase
7352 : public ConstStmtVisitor<Derived, bool> {
7353private:
7354 Derived &getDerived() { return static_cast<Derived&>(*this); }
7355 bool DerivedSuccess(const APValue &V, const Expr *E) {
7356 return getDerived().Success(V, E);
7357 }
7358 bool DerivedZeroInitialization(const Expr *E) {
7359 return getDerived().ZeroInitialization(E);
7360 }
7361
7362 // Check whether a conditional operator with a non-constant condition is a
7363 // potential constant expression. If neither arm is a potential constant
7364 // expression, then the conditional operator is not either.
7365 template<typename ConditionalOperator>
7366 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7367 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "clang/lib/AST/ExprConstant.cpp", 7367, __extension__ __PRETTY_FUNCTION__
))
;
7368
7369 // Speculatively evaluate both arms.
7370 SmallVector<PartialDiagnosticAt, 8> Diag;
7371 {
7372 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7373 StmtVisitorTy::Visit(E->getFalseExpr());
7374 if (Diag.empty())
7375 return;
7376 }
7377
7378 {
7379 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7380 Diag.clear();
7381 StmtVisitorTy::Visit(E->getTrueExpr());
7382 if (Diag.empty())
7383 return;
7384 }
7385
7386 Error(E, diag::note_constexpr_conditional_never_const);
7387 }
7388
7389
7390 template<typename ConditionalOperator>
7391 bool HandleConditionalOperator(const ConditionalOperator *E) {
7392 bool BoolResult;
7393 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7394 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7395 CheckPotentialConstantConditional(E);
7396 return false;
7397 }
7398 if (Info.noteFailure()) {
7399 StmtVisitorTy::Visit(E->getTrueExpr());
7400 StmtVisitorTy::Visit(E->getFalseExpr());
7401 }
7402 return false;
7403 }
7404
7405 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7406 return StmtVisitorTy::Visit(EvalExpr);
7407 }
7408
7409protected:
7410 EvalInfo &Info;
7411 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7412 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7413
7414 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7415 return Info.CCEDiag(E, D);
7416 }
7417
7418 bool ZeroInitialization(const Expr *E) { return Error(E); }
7419
7420 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7421 unsigned BuiltinOp = E->getBuiltinCallee();
7422 return BuiltinOp != 0 &&
7423 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7424 }
7425
7426public:
7427 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7428
7429 EvalInfo &getEvalInfo() { return Info; }
7430
7431 /// Report an evaluation error. This should only be called when an error is
7432 /// first discovered. When propagating an error, just return false.
7433 bool Error(const Expr *E, diag::kind D) {
7434 Info.FFDiag(E, D);
7435 return false;
7436 }
7437 bool Error(const Expr *E) {
7438 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7439 }
7440
7441 bool VisitStmt(const Stmt *) {
7442 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", 7442)
;
7443 }
7444 bool VisitExpr(const Expr *E) {
7445 return Error(E);
7446 }
7447
7448 bool VisitConstantExpr(const ConstantExpr *E) {
7449 if (E->hasAPValueResult())
7450 return DerivedSuccess(E->getAPValueResult(), E);
7451
7452 return StmtVisitorTy::Visit(E->getSubExpr());
7453 }
7454
7455 bool VisitParenExpr(const ParenExpr *E)
7456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7457 bool VisitUnaryExtension(const UnaryOperator *E)
7458 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7459 bool VisitUnaryPlus(const UnaryOperator *E)
7460 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7461 bool VisitChooseExpr(const ChooseExpr *E)
7462 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7463 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7464 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7465 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7466 { return StmtVisitorTy::Visit(E->getReplacement()); }
7467 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7468 TempVersionRAII RAII(*Info.CurrentCall);
7469 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7470 return StmtVisitorTy::Visit(E->getExpr());
7471 }
7472 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7473 TempVersionRAII RAII(*Info.CurrentCall);
7474 // The initializer may not have been parsed yet, or might be erroneous.
7475 if (!E->getExpr())
7476 return Error(E);
7477 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7478 return StmtVisitorTy::Visit(E->getExpr());
7479 }
7480
7481 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7482 FullExpressionRAII Scope(Info);
7483 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7484 }
7485
7486 // Temporaries are registered when created, so we don't care about
7487 // CXXBindTemporaryExpr.
7488 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7489 return StmtVisitorTy::Visit(E->getSubExpr());
7490 }
7491
7492 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7493 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7494 return static_cast<Derived*>(this)->VisitCastExpr(E);
7495 }
7496 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7497 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7498 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7499 return static_cast<Derived*>(this)->VisitCastExpr(E);
7500 }
7501 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7502 return static_cast<Derived*>(this)->VisitCastExpr(E);
7503 }
7504
7505 bool VisitBinaryOperator(const BinaryOperator *E) {
7506 switch (E->getOpcode()) {
7507 default:
7508 return Error(E);
7509
7510 case BO_Comma:
7511 VisitIgnoredValue(E->getLHS());
7512 return StmtVisitorTy::Visit(E->getRHS());
7513
7514 case BO_PtrMemD:
7515 case BO_PtrMemI: {
7516 LValue Obj;
7517 if (!HandleMemberPointerAccess(Info, E, Obj))
7518 return false;
7519 APValue Result;
7520 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7521 return false;
7522 return DerivedSuccess(Result, E);
7523 }
7524 }
7525 }
7526
7527 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7528 return StmtVisitorTy::Visit(E->getSemanticForm());
7529 }
7530
7531 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7532 // Evaluate and cache the common expression. We treat it as a temporary,
7533 // even though it's not quite the same thing.
7534 LValue CommonLV;
7535 if (!Evaluate(Info.CurrentCall->createTemporary(
7536 E->getOpaqueValue(),
7537 getStorageType(Info.Ctx, E->getOpaqueValue()),
7538 ScopeKind::FullExpression, CommonLV),
7539 Info, E->getCommon()))
7540 return false;
7541
7542 return HandleConditionalOperator(E);
7543 }
7544
7545 bool VisitConditionalOperator(const ConditionalOperator *E) {
7546 bool IsBcpCall = false;
7547 // If the condition (ignoring parens) is a __builtin_constant_p call,
7548 // the result is a constant expression if it can be folded without
7549 // side-effects. This is an important GNU extension. See GCC PR38377
7550 // for discussion.
7551 if (const CallExpr *CallCE =
7552 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7553 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7554 IsBcpCall = true;
7555
7556 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7557 // constant expression; we can't check whether it's potentially foldable.
7558 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7559 // it would return 'false' in this mode.
7560 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7561 return false;
7562
7563 FoldConstant Fold(Info, IsBcpCall);
7564 if (!HandleConditionalOperator(E)) {
7565 Fold.keepDiagnostics();
7566 return false;
7567 }
7568
7569 return true;
7570 }
7571
7572 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7573 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7574 return DerivedSuccess(*Value, E);
7575
7576 const Expr *Source = E->getSourceExpr();
7577 if (!Source)
7578 return Error(E);
7579 if (Source == E) {
7580 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", 7580, __extension__ __PRETTY_FUNCTION__
))
;
7581 return Error(E);
7582 }
7583 return StmtVisitorTy::Visit(Source);
7584 }
7585
7586 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7587 for (const Expr *SemE : E->semantics()) {
7588 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7589 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7590 // result expression: there could be two different LValues that would
7591 // refer to the same object in that case, and we can't model that.
7592 if (SemE == E->getResultExpr())
7593 return Error(E);
7594
7595 // Unique OVEs get evaluated if and when we encounter them when
7596 // emitting the rest of the semantic form, rather than eagerly.
7597 if (OVE->isUnique())
7598 continue;
7599
7600 LValue LV;
7601 if (!Evaluate(Info.CurrentCall->createTemporary(
7602 OVE, getStorageType(Info.Ctx, OVE),
7603 ScopeKind::FullExpression, LV),
7604 Info, OVE->getSourceExpr()))
7605 return false;
7606 } else if (SemE == E->getResultExpr()) {
7607 if (!StmtVisitorTy::Visit(SemE))
7608 return false;
7609 } else {
7610 if (!EvaluateIgnoredValue(Info, SemE))
7611 return false;
7612 }
7613 }
7614 return true;
7615 }
7616
7617 bool VisitCallExpr(const CallExpr *E) {
7618 APValue Result;
7619 if (!handleCallExpr(E, Result, nullptr))
7620 return false;
7621 return DerivedSuccess(Result, E);
7622 }
7623
7624 bool handleCallExpr(const CallExpr *E, APValue &Result,
7625 const LValue *ResultSlot) {
7626 CallScopeRAII CallScope(Info);
7627
7628 const Expr *Callee = E->getCallee()->IgnoreParens();
7629 QualType CalleeType = Callee->getType();
7630
7631 const FunctionDecl *FD = nullptr;
7632 LValue *This = nullptr, ThisVal;
7633 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7634 bool HasQualifier = false;
7635
7636 CallRef Call;
7637
7638 // Extract function decl and 'this' pointer from the callee.
7639 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7640 const CXXMethodDecl *Member = nullptr;
7641 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7642 // Explicit bound member calls, such as x.f() or p->g();
7643 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7644 return false;
7645 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7646 if (!Member)
7647 return Error(Callee);
7648 This = &ThisVal;
7649 HasQualifier = ME->hasQualifier();
7650 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7651 // Indirect bound member calls ('.*' or '->*').
7652 const ValueDecl *D =
7653 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7654 if (!D)
7655 return false;
7656 Member = dyn_cast<CXXMethodDecl>(D);
7657 if (!Member)
7658 return Error(Callee);
7659 This = &ThisVal;
7660 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7661 if (!Info.getLangOpts().CPlusPlus20)
7662 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7663 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7664 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7665 } else
7666 return Error(Callee);
7667 FD = Member;
7668 } else if (CalleeType->isFunctionPointerType()) {
7669 LValue CalleeLV;
7670 if (!EvaluatePointer(Callee, CalleeLV, Info))
7671 return false;
7672
7673 if (!CalleeLV.getLValueOffset().isZero())
7674 return Error(Callee);
7675 FD = dyn_cast_or_null<FunctionDecl>(
7676 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7677 if (!FD)
7678 return Error(Callee);
7679 // Don't call function pointers which have been cast to some other type.
7680 // Per DR (no number yet), the caller and callee can differ in noexcept.
7681 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7682 CalleeType->getPointeeType(), FD->getType())) {
7683 return Error(E);
7684 }
7685
7686 // For an (overloaded) assignment expression, evaluate the RHS before the
7687 // LHS.
7688 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7689 if (OCE && OCE->isAssignmentOp()) {
7690 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", 7690, __extension__ __PRETTY_FUNCTION__
))
;
7691 Call = Info.CurrentCall->createCall(FD);
7692 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7693 Info, FD, /*RightToLeft=*/true))
7694 return false;
7695 }
7696
7697 // Overloaded operator calls to member functions are represented as normal
7698 // calls with '*this' as the first argument.
7699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7700 if (MD && !MD->isStatic()) {
7701 // FIXME: When selecting an implicit conversion for an overloaded
7702 // operator delete, we sometimes try to evaluate calls to conversion
7703 // operators without a 'this' parameter!
7704 if (Args.empty())
7705 return Error(E);
7706
7707 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7708 return false;
7709 This = &ThisVal;
7710
7711 // If this is syntactically a simple assignment using a trivial
7712 // assignment operator, start the lifetimes of union members as needed,
7713 // per C++20 [class.union]5.
7714 if (Info.getLangOpts().CPlusPlus20 && OCE &&
7715 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7716 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7717 return false;
7718
7719 Args = Args.slice(1);
7720 } else if (MD && MD->isLambdaStaticInvoker()) {
7721 // Map the static invoker for the lambda back to the call operator.
7722 // Conveniently, we don't have to slice out the 'this' argument (as is
7723 // being done for the non-static case), since a static member function
7724 // doesn't have an implicit argument passed in.
7725 const CXXRecordDecl *ClosureClass = MD->getParent();
7726 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", 7728, __extension__ __PRETTY_FUNCTION__
))
7727 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", 7728, __extension__ __PRETTY_FUNCTION__
))
7728 "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", 7728, __extension__ __PRETTY_FUNCTION__
))
;
7729
7730 const CXXMethodDecl *LambdaCallOp =
7731 ClosureClass->getLambdaCallOperator();
7732
7733 // Set 'FD', the function that will be called below, to the call
7734 // operator. If the closure object represents a generic lambda, find
7735 // the corresponding specialization of the call operator.
7736
7737 if (ClosureClass->isGenericLambda()) {
7738 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", 7740, __extension__ __PRETTY_FUNCTION__
))
7739 "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", 7740, __extension__ __PRETTY_FUNCTION__
))
7740 "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", 7740, __extension__ __PRETTY_FUNCTION__
))
;
7741 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7742 FunctionTemplateDecl *CallOpTemplate =
7743 LambdaCallOp->getDescribedFunctionTemplate();
7744 void *InsertPos = nullptr;
7745 FunctionDecl *CorrespondingCallOpSpecialization =
7746 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7747 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", 7749, __extension__ __PRETTY_FUNCTION__
))
7748 "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", 7749, __extension__ __PRETTY_FUNCTION__
))
7749 "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", 7749, __extension__ __PRETTY_FUNCTION__
))
;
7750 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7751 } else
7752 FD = LambdaCallOp;
7753 } else if (FD->isReplaceableGlobalAllocationFunction()) {
7754 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7755 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7756 LValue Ptr;
7757 if (!HandleOperatorNewCall(Info, E, Ptr))
7758 return false;
7759 Ptr.moveInto(Result);
7760 return CallScope.destroy();
7761 } else {
7762 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7763 }
7764 }
7765 } else
7766 return Error(E);
7767
7768 // Evaluate the arguments now if we've not already done so.
7769 if (!Call) {
7770 Call = Info.CurrentCall->createCall(FD);
7771 if (!EvaluateArgs(Args, Call, Info, FD))
7772 return false;
7773 }
7774
7775 SmallVector<QualType, 4> CovariantAdjustmentPath;
7776 if (This) {
7777 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7778 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7779 // Perform virtual dispatch, if necessary.
7780 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7781 CovariantAdjustmentPath);
7782 if (!FD)
7783 return false;
7784 } else {
7785 // Check that the 'this' pointer points to an object of the right type.
7786 // FIXME: If this is an assignment operator call, we may need to change
7787 // the active union member before we check this.
7788 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7789 return false;
7790 }
7791 }
7792
7793 // Destructor calls are different enough that they have their own codepath.
7794 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7795 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", 7795, __extension__ __PRETTY_FUNCTION__
))
;
7796 return HandleDestruction(Info, E, *This,
7797 Info.Ctx.getRecordType(DD->getParent())) &&
7798 CallScope.destroy();
7799 }
7800
7801 const FunctionDecl *Definition = nullptr;
7802 Stmt *Body = FD->getBody(Definition);
7803
7804 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7805 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7806 Body, Info, Result, ResultSlot))
7807 return false;
7808
7809 if (!CovariantAdjustmentPath.empty() &&
7810 !HandleCovariantReturnAdjustment(Info, E, Result,
7811 CovariantAdjustmentPath))
7812 return false;
7813
7814 return CallScope.destroy();
7815 }
7816
7817 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7818 return StmtVisitorTy::Visit(E->getInitializer());
7819 }
7820 bool VisitInitListExpr(const InitListExpr *E) {
7821 if (E->getNumInits() == 0)
7822 return DerivedZeroInitialization(E);
7823 if (E->getNumInits() == 1)
7824 return StmtVisitorTy::Visit(E->getInit(0));
7825 return Error(E);
7826 }
7827 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7828 return DerivedZeroInitialization(E);
7829 }
7830 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7831 return DerivedZeroInitialization(E);
7832 }
7833 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7834 return DerivedZeroInitialization(E);
7835 }
7836
7837 /// A member expression where the object is a prvalue is itself a prvalue.
7838 bool VisitMemberExpr(const MemberExpr *E) {
7839 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", 7840, __extension__ __PRETTY_FUNCTION__
))
7840 "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", 7840, __extension__ __PRETTY_FUNCTION__
))
;
7841 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", 7841, __extension__ __PRETTY_FUNCTION__
))
;
7842
7843 APValue Val;
7844 if (!Evaluate(Val, Info, E->getBase()))
7845 return false;
7846
7847 QualType BaseTy = E->getBase()->getType();
7848
7849 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7850 if (!FD) return Error(E);
7851 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", 7851, __extension__ __PRETTY_FUNCTION__
))
;
7852 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", 7853, __extension__ __PRETTY_FUNCTION__
))
7853 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", 7853, __extension__ __PRETTY_FUNCTION__
))
;
7854
7855 // Note: there is no lvalue base here. But this case should only ever
7856 // happen in C or in C++98, where we cannot be evaluating a constexpr
7857 // constructor, which is the only case the base matters.
7858 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7859 SubobjectDesignator Designator(BaseTy);
7860 Designator.addDeclUnchecked(FD);
7861
7862 APValue Result;
7863 return extractSubobject(Info, E, Obj, Designator, Result) &&
7864 DerivedSuccess(Result, E);
7865 }
7866
7867 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7868 APValue Val;
7869 if (!Evaluate(Val, Info, E->getBase()))
7870 return false;
7871
7872 if (Val.isVector()) {
7873 SmallVector<uint32_t, 4> Indices;
7874 E->getEncodedElementAccess(Indices);
7875 if (Indices.size() == 1) {
7876 // Return scalar.
7877 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7878 } else {
7879 // Construct new APValue vector.
7880 SmallVector<APValue, 4> Elts;
7881 for (unsigned I = 0; I < Indices.size(); ++I) {
7882 Elts.push_back(Val.getVectorElt(Indices[I]));
7883 }
7884 APValue VecResult(Elts.data(), Indices.size());
7885 return DerivedSuccess(VecResult, E);
7886 }
7887 }
7888
7889 return false;
7890 }
7891
7892 bool VisitCastExpr(const CastExpr *E) {
7893 switch (E->getCastKind()) {
7894 default:
7895 break;
7896
7897 case CK_AtomicToNonAtomic: {
7898 APValue AtomicVal;
7899 // This does not need to be done in place even for class/array types:
7900 // atomic-to-non-atomic conversion implies copying the object
7901 // representation.
7902 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7903 return false;
7904 return DerivedSuccess(AtomicVal, E);
7905 }
7906
7907 case CK_NoOp:
7908 case CK_UserDefinedConversion:
7909 return StmtVisitorTy::Visit(E->getSubExpr());
7910
7911 case CK_LValueToRValue: {
7912 LValue LVal;
7913 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7914 return false;
7915 APValue RVal;
7916 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7917 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7918 LVal, RVal))
7919 return false;
7920 return DerivedSuccess(RVal, E);
7921 }
7922 case CK_LValueToRValueBitCast: {
7923 APValue DestValue, SourceValue;
7924 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7925 return false;
7926 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7927 return false;
7928 return DerivedSuccess(DestValue, E);
7929 }
7930
7931 case CK_AddressSpaceConversion: {
7932 APValue Value;
7933 if (!Evaluate(Value, Info, E->getSubExpr()))
7934 return false;
7935 return DerivedSuccess(Value, E);
7936 }
7937 }
7938
7939 return Error(E);
7940 }
7941
7942 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7943 return VisitUnaryPostIncDec(UO);
7944 }
7945 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7946 return VisitUnaryPostIncDec(UO);
7947 }
7948 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7949 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7950 return Error(UO);
7951
7952 LValue LVal;
7953 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7954 return false;
7955 APValue RVal;
7956 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7957 UO->isIncrementOp(), &RVal))
7958 return false;
7959 return DerivedSuccess(RVal, UO);
7960 }
7961
7962 bool VisitStmtExpr(const StmtExpr *E) {
7963 // We will have checked the full-expressions inside the statement expression
7964 // when they were completed, and don't need to check them again now.
7965 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
7966 false);
7967
7968 const CompoundStmt *CS = E->getSubStmt();
7969 if (CS->body_empty())
7970 return true;
7971
7972 BlockScopeRAII Scope(Info);
7973 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7974 BE = CS->body_end();
7975 /**/; ++BI) {
7976 if (BI + 1 == BE) {
7977 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7978 if (!FinalExpr) {
7979 Info.FFDiag((*BI)->getBeginLoc(),
7980 diag::note_constexpr_stmt_expr_unsupported);
7981 return false;
7982 }
7983 return this->Visit(FinalExpr) && Scope.destroy();
7984 }
7985
7986 APValue ReturnValue;
7987 StmtResult Result = { ReturnValue, nullptr };
7988 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7989 if (ESR != ESR_Succeeded) {
7990 // FIXME: If the statement-expression terminated due to 'return',
7991 // 'break', or 'continue', it would be nice to propagate that to
7992 // the outer statement evaluation rather than bailing out.
7993 if (ESR != ESR_Failed)
7994 Info.FFDiag((*BI)->getBeginLoc(),
7995 diag::note_constexpr_stmt_expr_unsupported);
7996 return false;
7997 }
7998 }
7999
8000 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", 8000)
;
8001 }
8002
8003 /// Visit a value which is evaluated, but whose value is ignored.
8004 void VisitIgnoredValue(const Expr *E) {
8005 EvaluateIgnoredValue(Info, E);
8006 }
8007
8008 /// Potentially visit a MemberExpr's base expression.
8009 void VisitIgnoredBaseExpression(const Expr *E) {
8010 // While MSVC doesn't evaluate the base expression, it does diagnose the
8011 // presence of side-effecting behavior.
8012 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8013 return;
8014 VisitIgnoredValue(E);
8015 }
8016};
8017
8018} // namespace
8019
8020//===----------------------------------------------------------------------===//
8021// Common base class for lvalue and temporary evaluation.
8022//===----------------------------------------------------------------------===//
8023namespace {
8024template<class Derived>
8025class LValueExprEvaluatorBase
8026 : public ExprEvaluatorBase<Derived> {
8027protected:
8028 LValue &Result;
8029 bool InvalidBaseOK;
8030 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8031 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8032
8033 bool Success(APValue::LValueBase B) {
8034 Result.set(B);
8035 return true;
8036 }
8037
8038 bool evaluatePointer(const Expr *E, LValue &Result) {
8039 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8040 }
8041
8042public:
8043 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8044 : ExprEvaluatorBaseTy(Info), Result(Result),
8045 InvalidBaseOK(InvalidBaseOK) {}
8046
8047 bool Success(const APValue &V, const Expr *E) {
8048 Result.setFrom(this->Info.Ctx, V);
8049 return true;
8050 }
8051
8052 bool VisitMemberExpr(const MemberExpr *E) {
8053 // Handle non-static data members.
8054 QualType BaseTy;
8055 bool EvalOK;
8056 if (E->isArrow()) {
8057 EvalOK = evaluatePointer(E->getBase(), Result);
8058 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8059 } else if (E->getBase()->isPRValue()) {
8060 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", 8060, __extension__ __PRETTY_FUNCTION__
))
;
8061 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8062 BaseTy = E->getBase()->getType();
8063 } else {
8064 EvalOK = this->Visit(E->getBase());
8065 BaseTy = E->getBase()->getType();
8066 }
8067 if (!EvalOK) {
8068 if (!InvalidBaseOK)
8069 return false;
8070 Result.setInvalid(E);
8071 return true;
8072 }
8073
8074 const ValueDecl *MD = E->getMemberDecl();
8075 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8076 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", 8077, __extension__ __PRETTY_FUNCTION__
))
8077 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", 8077, __extension__ __PRETTY_FUNCTION__
))
;
8078 (void)BaseTy;
8079 if (!HandleLValueMember(this->Info, E, Result, FD))
8080 return false;
8081 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8082 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8083 return false;
8084 } else
8085 return this->Error(E);
8086
8087 if (MD->getType()->isReferenceType()) {
8088 APValue RefValue;
8089 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8090 RefValue))
8091 return false;
8092 return Success(RefValue, E);
8093 }
8094 return true;
8095 }
8096
8097 bool VisitBinaryOperator(const BinaryOperator *E) {
8098 switch (E->getOpcode()) {
8099 default:
8100 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8101
8102 case BO_PtrMemD:
8103 case BO_PtrMemI:
8104 return HandleMemberPointerAccess(this->Info, E, Result);
8105 }
8106 }
8107
8108 bool VisitCastExpr(const CastExpr *E) {
8109 switch (E->getCastKind()) {
8110 default:
8111 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8112
8113 case CK_DerivedToBase:
8114 case CK_UncheckedDerivedToBase:
8115 if (!this->Visit(E->getSubExpr()))
8116 return false;
8117
8118 // Now figure out the necessary offset to add to the base LV to get from
8119 // the derived class to the base class.
8120 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8121 Result);
8122 }
8123 }
8124};
8125}
8126
8127//===----------------------------------------------------------------------===//
8128// LValue Evaluation
8129//
8130// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8131// function designators (in C), decl references to void objects (in C), and
8132// temporaries (if building with -Wno-address-of-temporary).
8133//
8134// LValue evaluation produces values comprising a base expression of one of the
8135// following types:
8136// - Declarations
8137// * VarDecl
8138// * FunctionDecl
8139// - Literals
8140// * CompoundLiteralExpr in C (and in global scope in C++)
8141// * StringLiteral
8142// * PredefinedExpr
8143// * ObjCStringLiteralExpr
8144// * ObjCEncodeExpr
8145// * AddrLabelExpr
8146// * BlockExpr
8147// * CallExpr for a MakeStringConstant builtin
8148// - typeid(T) expressions, as TypeInfoLValues
8149// - Locals and temporaries
8150// * MaterializeTemporaryExpr
8151// * Any Expr, with a CallIndex indicating the function in which the temporary
8152// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8153// from the AST (FIXME).
8154// * A MaterializeTemporaryExpr that has static storage duration, with no
8155// CallIndex, for a lifetime-extended temporary.
8156// * The ConstantExpr that is currently being evaluated during evaluation of an
8157// immediate invocation.
8158// plus an offset in bytes.
8159//===----------------------------------------------------------------------===//
8160namespace {
8161class LValueExprEvaluator
8162 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8163public:
8164 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8165 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8166
8167 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8168 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8169
8170 bool VisitCallExpr(const CallExpr *E);
8171 bool VisitDeclRefExpr(const DeclRefExpr *E);
8172 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8173 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8174 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8175 bool VisitMemberExpr(const MemberExpr *E);
8176 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8177 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8178 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8179 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8180 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8181 bool VisitUnaryDeref(const UnaryOperator *E);
8182 bool VisitUnaryReal(const UnaryOperator *E);
8183 bool VisitUnaryImag(const UnaryOperator *E);
8184 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8185 return VisitUnaryPreIncDec(UO);
8186 }
8187 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8188 return VisitUnaryPreIncDec(UO);
8189 }
8190 bool VisitBinAssign(const BinaryOperator *BO);
8191 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8192
8193 bool VisitCastExpr(const CastExpr *E) {
8194 switch (E->getCastKind()) {
8195 default:
8196 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8197
8198 case CK_LValueBitCast:
8199 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8200 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8201 if (!Visit(E->getSubExpr()))
8202 return false;
8203 Result.Designator.setInvalid();
8204 return true;
8205
8206 case CK_BaseToDerived:
8207 if (!Visit(E->getSubExpr()))
8208 return false;
8209 return HandleBaseToDerivedCast(Info, E, Result);
8210
8211 case CK_Dynamic:
8212 if (!Visit(E->getSubExpr()))
8213 return false;
8214 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8215 }
8216 }
8217};
8218} // end anonymous namespace
8219
8220/// Evaluate an expression as an lvalue. This can be legitimately called on
8221/// expressions which are not glvalues, in three cases:
8222/// * function designators in C, and
8223/// * "extern void" objects
8224/// * @selector() expressions in Objective-C
8225static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8226 bool InvalidBaseOK) {
8227 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 8227, __extension__ __PRETTY_FUNCTION__))
;
8228 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", 8229, __extension__ __PRETTY_FUNCTION__
))
8229 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", 8229, __extension__ __PRETTY_FUNCTION__
))
;
8230 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8231}
8232
8233bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8234 const NamedDecl *D = E->getDecl();
8235 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8236 UnnamedGlobalConstantDecl>(D))
8237 return Success(cast<ValueDecl>(D));
8238 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8239 return VisitVarDecl(E, VD);
8240 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8241 return Visit(BD->getBinding());
8242 return Error(E);
8243}
8244
8245
8246bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8247
8248 // If we are within a lambda's call operator, check whether the 'VD' referred
8249 // to within 'E' actually represents a lambda-capture that maps to a
8250 // data-member/field within the closure object, and if so, evaluate to the
8251 // field or what the field refers to.
8252 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8253 isa<DeclRefExpr>(E) &&
8254 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8255 // We don't always have a complete capture-map when checking or inferring if
8256 // the function call operator meets the requirements of a constexpr function
8257 // - but we don't need to evaluate the captures to determine constexprness
8258 // (dcl.constexpr C++17).
8259 if (Info.checkingPotentialConstantExpression())
8260 return false;
8261
8262 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8263 // Start with 'Result' referring to the complete closure object...
8264 Result = *Info.CurrentCall->This;
8265 // ... then update it to refer to the field of the closure object
8266 // that represents the capture.
8267 if (!HandleLValueMember(Info, E, Result, FD))
8268 return false;
8269 // And if the field is of reference type, update 'Result' to refer to what
8270 // the field refers to.
8271 if (FD->getType()->isReferenceType()) {
8272 APValue RVal;
8273 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8274 RVal))
8275 return false;
8276 Result.setFrom(Info.Ctx, RVal);
8277 }
8278 return true;
8279 }
8280 }
8281
8282 CallStackFrame *Frame = nullptr;
8283 unsigned Version = 0;
8284 if (VD->hasLocalStorage()) {
8285 // Only if a local variable was declared in the function currently being
8286 // evaluated, do we expect to be able to find its value in the current
8287 // frame. (Otherwise it was likely declared in an enclosing context and
8288 // could either have a valid evaluatable value (for e.g. a constexpr
8289 // variable) or be ill-formed (and trigger an appropriate evaluation
8290 // diagnostic)).
8291 CallStackFrame *CurrFrame = Info.CurrentCall;
8292 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8293 // Function parameters are stored in some caller's frame. (Usually the
8294 // immediate caller, but for an inherited constructor they may be more
8295 // distant.)
8296 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8297 if (CurrFrame->Arguments) {
8298 VD = CurrFrame->Arguments.getOrigParam(PVD);
8299 Frame =
8300 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8301 Version = CurrFrame->Arguments.Version;
8302 }
8303 } else {
8304 Frame = CurrFrame;
8305 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8306 }
8307 }
8308 }
8309
8310 if (!VD->getType()->isReferenceType()) {
8311 if (Frame) {
8312 Result.set({VD, Frame->Index, Version});
8313 return true;
8314 }
8315 return Success(VD);
8316 }
8317
8318 if (!Info.getLangOpts().CPlusPlus11) {
8319 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8320 << VD << VD->getType();
8321 Info.Note(VD->getLocation(), diag::note_declared_at);
8322 }
8323
8324 APValue *V;
8325 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8326 return false;
8327 if (!V->hasValue()) {
8328 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8329 // adjust the diagnostic to say that.
8330 if (!Info.checkingPotentialConstantExpression())
8331 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8332 return false;
8333 }
8334 return Success(*V, E);
8335}
8336
8337bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8338 if (!IsConstantEvaluatedBuiltinCall(E))
8339 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8340
8341 switch (E->getBuiltinCallee()) {
8342 default:
8343 return false;
8344 case Builtin::BIas_const:
8345 case Builtin::BIforward:
8346 case Builtin::BImove:
8347 case Builtin::BImove_if_noexcept:
8348 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8349 return Visit(E->getArg(0));
8350 break;
8351 }
8352
8353 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8354}
8355
8356bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8357 const MaterializeTemporaryExpr *E) {
8358 // Walk through the expression to find the materialized temporary itself.
8359 SmallVector<const Expr *, 2> CommaLHSs;
8360 SmallVector<SubobjectAdjustment, 2> Adjustments;
8361 const Expr *Inner =
8362 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8363
8364 // If we passed any comma operators, evaluate their LHSs.
8365 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8366 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8367 return false;
8368
8369 // A materialized temporary with static storage duration can appear within the
8370 // result of a constant expression evaluation, so we need to preserve its
8371 // value for use outside this evaluation.
8372 APValue *Value;
8373 if (E->getStorageDuration() == SD_Static) {
8374 // FIXME: What about SD_Thread?
8375 Value = E->getOrCreateValue(true);
8376 *Value = APValue();
8377 Result.set(E);
8378 } else {
8379 Value = &Info.CurrentCall->createTemporary(
8380 E, E->getType(),
8381 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8382 : ScopeKind::Block,
8383 Result);
8384 }
8385
8386 QualType Type = Inner->getType();
8387
8388 // Materialize the temporary itself.
8389 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8390 *Value = APValue();
8391 return false;
8392 }
8393
8394 // Adjust our lvalue to refer to the desired subobject.
8395 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8396 --I;
8397 switch (Adjustments[I].Kind) {
8398 case SubobjectAdjustment::DerivedToBaseAdjustment:
8399 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8400 Type, Result))
8401 return false;
8402 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8403 break;
8404
8405 case SubobjectAdjustment::FieldAdjustment:
8406 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8407 return false;
8408 Type = Adjustments[I].Field->getType();
8409 break;
8410
8411 case SubobjectAdjustment::MemberPointerAdjustment:
8412 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8413 Adjustments[I].Ptr.RHS))
8414 return false;
8415 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8416 break;
8417 }
8418 }
8419
8420 return true;
8421}
8422
8423bool
8424LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8425 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", 8426, __extension__ __PRETTY_FUNCTION__
))
8426 "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", 8426, __extension__ __PRETTY_FUNCTION__
))
;
8427 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8428 // only see this when folding in C, so there's no standard to follow here.
8429 return Success(E);
8430}
8431
8432bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8433 TypeInfoLValue TypeInfo;
8434
8435 if (!E->isPotentiallyEvaluated()) {
8436 if (E->isTypeOperand())
8437 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8438 else
8439 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8440 } else {
8441 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8442 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8443 << E->getExprOperand()->getType()
8444 << E->getExprOperand()->getSourceRange();
8445 }
8446
8447 if (!Visit(E->getExprOperand()))
8448 return false;
8449
8450 Optional<DynamicType> DynType =
8451 ComputeDynamicType(Info, E, Result, AK_TypeId);
8452 if (!DynType)
8453 return false;
8454
8455 TypeInfo =
8456 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8457 }
8458
8459 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8460}
8461
8462bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8463 return Success(E->getGuidDecl());
8464}
8465
8466bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8467 // Handle static data members.
8468 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8469 VisitIgnoredBaseExpression(E->getBase());
8470 return VisitVarDecl(E, VD);
8471 }
8472
8473 // Handle static member functions.
8474 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8475 if (MD->isStatic()) {
8476 VisitIgnoredBaseExpression(E->getBase());
8477 return Success(MD);
8478 }
8479 }
8480
8481 // Handle non-static data members.
8482 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8483}
8484
8485bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8486 // FIXME: Deal with vectors as array subscript bases.
8487 if (E->getBase()->getType()->isVectorType() ||
8488 E->getBase()->getType()->isVLSTBuiltinType())
8489 return Error(E);
8490
8491 APSInt Index;
8492 bool Success = true;
8493
8494 // C++17's rules require us to evaluate the LHS first, regardless of which
8495 // side is the base.
8496 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8497 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8498 : !EvaluateInteger(SubExpr, Index, Info)) {
8499 if (!Info.noteFailure())
8500 return false;
8501 Success = false;
8502 }
8503 }
8504
8505 return Success &&
8506 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8507}
8508
8509bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8510 return evaluatePointer(E->getSubExpr(), Result);
8511}
8512
8513bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8514 if (!Visit(E->getSubExpr()))
8515 return false;
8516 // __real is a no-op on scalar lvalues.
8517 if (E->getSubExpr()->getType()->isAnyComplexType())
8518 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8519 return true;
8520}
8521
8522bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8523 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", 8524, __extension__ __PRETTY_FUNCTION__
))
8524 "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", 8524, __extension__ __PRETTY_FUNCTION__
))
;
8525 if (!Visit(E->getSubExpr()))
8526 return false;
8527 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8528 return true;
8529}
8530
8531bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8532 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8533 return Error(UO);
8534
8535 if (!this->Visit(UO->getSubExpr()))
8536 return false;
8537
8538 return handleIncDec(
8539 this->Info, UO, Result, UO->getSubExpr()->getType(),
8540 UO->isIncrementOp(), nullptr);
8541}
8542
8543bool LValueExprEvaluator::VisitCompoundAssignOperator(
8544 const CompoundAssignOperator *CAO) {
8545 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8546 return Error(CAO);
8547
8548 bool Success = true;
8549
8550 // C++17 onwards require that we evaluate the RHS first.
8551 APValue RHS;
8552 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8553 if (!Info.noteFailure())
8554 return false;
8555 Success = false;
8556 }
8557
8558 // The overall lvalue result is the result of evaluating the LHS.
8559 if (!this->Visit(CAO->getLHS()) || !Success)
8560 return false;
8561
8562 return handleCompoundAssignment(
8563 this->Info, CAO,
8564 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8565 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8566}
8567
8568bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8569 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8570 return Error(E);
8571
8572 bool Success = true;
8573
8574 // C++17 onwards require that we evaluate the RHS first.
8575 APValue NewVal;
8576 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8577 if (!Info.noteFailure())
8578 return false;
8579 Success = false;
8580 }
8581
8582 if (!this->Visit(E->getLHS()) || !Success)
8583 return false;
8584
8585 if (Info.getLangOpts().CPlusPlus20 &&
8586 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8587 return false;
8588
8589 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8590 NewVal);
8591}
8592
8593//===----------------------------------------------------------------------===//
8594// Pointer Evaluation
8595//===----------------------------------------------------------------------===//
8596
8597/// Attempts to compute the number of bytes available at the pointer
8598/// returned by a function with the alloc_size attribute. Returns true if we
8599/// were successful. Places an unsigned number into `Result`.
8600///
8601/// This expects the given CallExpr to be a call to a function with an
8602/// alloc_size attribute.
8603static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8604 const CallExpr *Call,
8605 llvm::APInt &Result) {
8606 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8607
8608 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", 8608, __extension__ __PRETTY_FUNCTION__
))
;
8609 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8610 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8611 if (Call->getNumArgs() <= SizeArgNo)
8612 return false;
8613
8614 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8615 Expr::EvalResult ExprResult;
8616 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8617 return false;
8618 Into = ExprResult.Val.getInt();
8619 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8620 return false;
8621 Into = Into.zext(BitsInSizeT);
8622 return true;
8623 };
8624
8625 APSInt SizeOfElem;
8626 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8627 return false;
8628
8629 if (!AllocSize->getNumElemsParam().isValid()) {
8630 Result = std::move(SizeOfElem);
8631 return true;
8632 }
8633
8634 APSInt NumberOfElems;
8635 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8636 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8637 return false;
8638
8639 bool Overflow;
8640 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8641 if (Overflow)
8642 return false;
8643
8644 Result = std::move(BytesAvailable);
8645 return true;
8646}
8647
8648/// Convenience function. LVal's base must be a call to an alloc_size
8649/// function.
8650static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8651 const LValue &LVal,
8652 llvm::APInt &Result) {
8653 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", 8654, __extension__ __PRETTY_FUNCTION__
))
8654 "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", 8654, __extension__ __PRETTY_FUNCTION__
))
;
8655 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8656 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8657 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8658}
8659
8660/// Attempts to evaluate the given LValueBase as the result of a call to
8661/// a function with the alloc_size attribute. If it was possible to do so, this
8662/// function will return true, make Result's Base point to said function call,
8663/// and mark Result's Base as invalid.
8664static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8665 LValue &Result) {
8666 if (Base.isNull())
8667 return false;
8668
8669 // Because we do no form of static analysis, we only support const variables.
8670 //
8671 // Additionally, we can't support parameters, nor can we support static
8672 // variables (in the latter case, use-before-assign isn't UB; in the former,
8673 // we have no clue what they'll be assigned to).
8674 const auto *VD =
8675 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8676 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8677 return false;
8678
8679 const Expr *Init = VD->getAnyInitializer();
8680 if (!Init || Init->getType().isNull())
8681 return false;
8682
8683 const Expr *E = Init->IgnoreParens();
8684 if (!tryUnwrapAllocSizeCall(E))
8685 return false;
8686
8687 // Store E instead of E unwrapped so that the type of the LValue's base is
8688 // what the user wanted.
8689 Result.setInvalid(E);
8690
8691 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8692 Result.addUnsizedArray(Info, E, Pointee);
8693 return true;
8694}
8695
8696namespace {
8697class PointerExprEvaluator
8698 : public ExprEvaluatorBase<PointerExprEvaluator> {
8699 LValue &Result;
8700 bool InvalidBaseOK;
8701
8702 bool Success(const Expr *E) {
8703 Result.set(E);
8704 return true;
8705 }
8706
8707 bool evaluateLValue(const Expr *E, LValue &Result) {
8708 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8709 }
8710
8711 bool evaluatePointer(const Expr *E, LValue &Result) {
8712 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8713 }
8714
8715 bool visitNonBuiltinCallExpr(const CallExpr *E);
8716public:
8717
8718 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8719 : ExprEvaluatorBaseTy(info), Result(Result),
8720 InvalidBaseOK(InvalidBaseOK) {}
8721
8722 bool Success(const APValue &V, const Expr *E) {
8723 Result.setFrom(Info.Ctx, V);
8724 return true;
8725 }
8726 bool ZeroInitialization(const Expr *E) {
8727 Result.setNull(Info.Ctx, E->getType());
8728 return true;
8729 }
8730
8731 bool VisitBinaryOperator(const BinaryOperator *E);
8732 bool VisitCastExpr(const CastExpr* E);
8733 bool VisitUnaryAddrOf(const UnaryOperator *E);
8734 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8735 { return Success(E); }
8736 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8737 if (E->isExpressibleAsConstantInitializer())
8738 return Success(E);
8739 if (Info.noteFailure())
8740 EvaluateIgnoredValue(Info, E->getSubExpr());
8741 return Error(E);
8742 }
8743 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8744 { return Success(E); }
8745 bool VisitCallExpr(const CallExpr *E);
8746 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8747 bool VisitBlockExpr(const BlockExpr *E) {
8748 if (!E->getBlockDecl()->hasCaptures())
8749 return Success(E);
8750 return Error(E);
8751 }
8752 bool VisitCXXThisExpr(const CXXThisExpr *E) {
8753 // Can't look at 'this' when checking a potential constant expression.
8754 if (Info.checkingPotentialConstantExpression())
8755 return false;
8756 if (!Info.CurrentCall->This) {
8757 if (Info.getLangOpts().CPlusPlus11)
8758 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8759 else
8760 Info.FFDiag(E);
8761 return false;
8762 }
8763 Result = *Info.CurrentCall->This;
8764 // If we are inside a lambda's call operator, the 'this' expression refers
8765 // to the enclosing '*this' object (either by value or reference) which is
8766 // either copied into the closure object's field that represents the '*this'
8767 // or refers to '*this'.
8768 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8769 // Ensure we actually have captured 'this'. (an error will have
8770 // been previously reported if not).
8771 if (!Info.CurrentCall->LambdaThisCaptureField)
8772 return false;
8773
8774 // Update 'Result' to refer to the data member/field of the closure object
8775 // that represents the '*this' capture.
8776 if (!HandleLValueMember(Info, E, Result,
8777 Info.CurrentCall->LambdaThisCaptureField))
8778 return false;
8779 // If we captured '*this' by reference, replace the field with its referent.
8780 if (Info.CurrentCall->LambdaThisCaptureField->getType()
8781 ->isPointerType()) {
8782 APValue RVal;
8783 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8784 RVal))
8785 return false;
8786
8787 Result.setFrom(Info.Ctx, RVal);
8788 }
8789 }
8790 return true;
8791 }
8792
8793 bool VisitCXXNewExpr(const CXXNewExpr *E);
8794
8795 bool VisitSourceLocExpr(const SourceLocExpr *E) {
8796 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", 8796, __extension__ __PRETTY_FUNCTION__
))
;
8797 APValue LValResult = E->EvaluateInContext(
8798 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8799 Result.setFrom(Info.Ctx, LValResult);
8800 return true;
8801 }
8802
8803 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8804 std::string ResultStr = E->ComputeName(Info.Ctx);
8805
8806 QualType CharTy = Info.Ctx.CharTy.withConst();
8807 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8808 ResultStr.size() + 1);
8809 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8810 ArrayType::Normal, 0);
8811
8812 StringLiteral *SL =
8813 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8814 /*Pascal*/ false, ArrayTy, E->getLocation());
8815
8816 evaluateLValue(SL, Result);
8817 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8818 return true;
8819 }
8820
8821 // FIXME: Missing: @protocol, @selector
8822};
8823} // end anonymous namespace
8824
8825static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8826 bool InvalidBaseOK) {
8827 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 8827, __extension__ __PRETTY_FUNCTION__))
;
8828 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", 8828, __extension__ __PRETTY_FUNCTION__
))
;
8829 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8830}
8831
8832bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8833 if (E->getOpcode() != BO_Add &&
8834 E->getOpcode() != BO_Sub)
8835 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8836
8837 const Expr *PExp = E->getLHS();
8838 const Expr *IExp = E->getRHS();
8839 if (IExp->getType()->isPointerType())
8840 std::swap(PExp, IExp);
8841
8842 bool EvalPtrOK = evaluatePointer(PExp, Result);
8843 if (!EvalPtrOK && !Info.noteFailure())
8844 return false;
8845
8846 llvm::APSInt Offset;
8847 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8848 return false;
8849
8850 if (E->getOpcode() == BO_Sub)
8851 negateAsSigned(Offset);
8852
8853 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8854 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8855}
8856
8857bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8858 return evaluateLValue(E->getSubExpr(), Result);
8859}
8860
8861// Is the provided decl 'std::source_location::current'?
8862static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8863 if (!FD)
8864 return false;
8865 const IdentifierInfo *FnII = FD->getIdentifier();
8866 if (!FnII || !FnII->isStr("current"))
8867 return false;
8868
8869 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8870 if (!RD)
8871 return false;
8872
8873 const IdentifierInfo *ClassII = RD->getIdentifier();
8874 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8875}
8876
8877bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8878 const Expr *SubExpr = E->getSubExpr();
8879
8880 switch (E->getCastKind()) {
8881 default:
8882 break;
8883 case CK_BitCast:
8884 case CK_CPointerToObjCPointerCast:
8885 case CK_BlockPointerToObjCPointerCast:
8886 case CK_AnyPointerToBlockPointerCast:
8887 case CK_AddressSpaceConversion:
8888 if (!Visit(SubExpr))
8889 return false;
8890 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8891 // permitted in constant expressions in C++11. Bitcasts from cv void* are
8892 // also static_casts, but we disallow them as a resolution to DR1312.
8893 if (!E->getType()->isVoidPointerType()) {
8894 // In some circumstances, we permit casting from void* to cv1 T*, when the
8895 // actual pointee object is actually a cv2 T.
8896 bool VoidPtrCastMaybeOK =
8897 !Result.InvalidBase && !Result.Designator.Invalid &&
8898 !Result.IsNullPtr &&
8899 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8900 E->getType()->getPointeeType());
8901 // 1. We'll allow it in std::allocator::allocate, and anything which that
8902 // calls.
8903 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8904 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8905 // We'll allow it in the body of std::source_location::current. GCC's
8906 // implementation had a parameter of type `void*`, and casts from
8907 // that back to `const __impl*` in its body.
8908 if (VoidPtrCastMaybeOK &&
8909 (Info.getStdAllocatorCaller("allocate") ||
8910 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8911 // Permitted.
8912 } else {
8913 Result.Designator.setInvalid();
8914 if (SubExpr->getType()->isVoidPointerType())
8915 CCEDiag(E, diag::note_constexpr_invalid_cast)
8916 << 3 << SubExpr->getType();
8917 else
8918 CCEDiag(E, diag::note_constexpr_invalid_cast)
8919 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8920 }
8921 }
8922 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8923 ZeroInitialization(E);
8924 return true;
8925
8926 case CK_DerivedToBase:
8927 case CK_UncheckedDerivedToBase:
8928 if (!evaluatePointer(E->getSubExpr(), Result))
8929 return false;
8930 if (!Result.Base && Result.Offset.isZero())
8931 return true;
8932
8933 // Now figure out the necessary offset to add to the base LV to get from
8934 // the derived class to the base class.
8935 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8936 castAs<PointerType>()->getPointeeType(),
8937 Result);
8938
8939 case CK_BaseToDerived:
8940 if (!Visit(E->getSubExpr()))
8941 return false;
8942 if (!Result.Base && Result.Offset.isZero())
8943 return true;
8944 return HandleBaseToDerivedCast(Info, E, Result);
8945
8946 case CK_Dynamic:
8947 if (!Visit(E->getSubExpr()))
8948 return false;
8949 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8950
8951 case CK_NullToPointer:
8952 VisitIgnoredValue(E->getSubExpr());
8953 return ZeroInitialization(E);
8954
8955 case CK_IntegralToPointer: {
8956 CCEDiag(E, diag::note_constexpr_invalid_cast)
8957 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8958
8959 APValue Value;
8960 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8961 break;
8962
8963 if (Value.isInt()) {
8964 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8965 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8966 Result.Base = (Expr*)nullptr;
8967 Result.InvalidBase = false;
8968 Result.Offset = CharUnits::fromQuantity(N);
8969 Result.Designator.setInvalid();
8970 Result.IsNullPtr = false;
8971 return true;
8972 } else {
8973 // Cast is of an lvalue, no need to change value.
8974 Result.setFrom(Info.Ctx, Value);
8975 return true;
8976 }
8977 }
8978
8979 case CK_ArrayToPointerDecay: {
8980 if (SubExpr->isGLValue()) {
8981 if (!evaluateLValue(SubExpr, Result))
8982 return false;
8983 } else {
8984 APValue &Value = Info.CurrentCall->createTemporary(
8985 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8986 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8987 return false;
8988 }
8989 // The result is a pointer to the first element of the array.
8990 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8991 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8992 Result.addArray(Info, E, CAT);
8993 else
8994 Result.addUnsizedArray(Info, E, AT->getElementType());
8995 return true;
8996 }
8997
8998 case CK_FunctionToPointerDecay:
8999 return evaluateLValue(SubExpr, Result);
9000
9001 case CK_LValueToRValue: {
9002 LValue LVal;
9003 if (!evaluateLValue(E->getSubExpr(), LVal))
9004 return false;
9005
9006 APValue RVal;
9007 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9008 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9009 LVal, RVal))
9010 return InvalidBaseOK &&
9011 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9012 return Success(RVal, E);
9013 }
9014 }
9015
9016 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9017}
9018
9019static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9020 UnaryExprOrTypeTrait ExprKind) {
9021 // C++ [expr.alignof]p3:
9022 // When alignof is applied to a reference type, the result is the
9023 // alignment of the referenced type.
9024 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9025 T = Ref->getPointeeType();
9026
9027 if (T.getQualifiers().hasUnaligned())
9028 return CharUnits::One();
9029
9030 const bool AlignOfReturnsPreferred =
9031 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9032
9033 // __alignof is defined to return the preferred alignment.
9034 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9035 // as well.
9036 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9037 return Info.Ctx.toCharUnitsFromBits(
9038 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9039 // alignof and _Alignof are defined to return the ABI alignment.
9040 else if (ExprKind == UETT_AlignOf)
9041 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9042 else
9043 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind"
, "clang/lib/AST/ExprConstant.cpp", 9043)
;
9044}
9045
9046static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9047 UnaryExprOrTypeTrait ExprKind) {
9048 E = E->IgnoreParens();
9049
9050 // The kinds of expressions that we have special-case logic here for
9051 // should be kept up to date with the special checks for those
9052 // expressions in Sema.
9053
9054 // alignof decl is always accepted, even if it doesn't make sense: we default
9055 // to 1 in those cases.
9056 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9057 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9058 /*RefAsPointee*/true);
9059
9060 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9061 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9062 /*RefAsPointee*/true);
9063
9064 return GetAlignOfType(Info, E->getType(), ExprKind);
9065}
9066
9067static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9068 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9069 return Info.Ctx.getDeclAlign(VD);
9070 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9071 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9072 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9073}
9074
9075/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9076/// __builtin_is_aligned and __builtin_assume_aligned.
9077static bool getAlignmentArgument(const Expr *E, QualType ForType,
9078 EvalInfo &Info, APSInt &Alignment) {
9079 if (!EvaluateInteger(E, Alignment, Info))
9080 return false;
9081 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9082 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9083 return false;
9084 }
9085 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9086 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9087 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9088 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9089 << MaxValue << ForType << Alignment;
9090 return false;
9091 }
9092 // Ensure both alignment and source value have the same bit width so that we
9093 // don't assert when computing the resulting value.
9094 APSInt ExtAlignment =
9095 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9096 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", 9097, __extension__ __PRETTY_FUNCTION__
))
9097 "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", 9097, __extension__ __PRETTY_FUNCTION__
))
;
9098 Alignment = ExtAlignment;
9099 assert(Alignment.getBitWidth() == SrcWidth)(static_cast <bool> (Alignment.getBitWidth() == SrcWidth
) ? void (0) : __assert_fail ("Alignment.getBitWidth() == SrcWidth"
, "clang/lib/AST/ExprConstant.cpp", 9099, __extension__ __PRETTY_FUNCTION__
))
;
9100 return true;
9101}
9102
9103// To be clear: this happily visits unsupported builtins. Better name welcomed.
9104bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9105 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9106 return true;
9107
9108 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9109 return false;
9110
9111 Result.setInvalid(E);
9112 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9113 Result.addUnsizedArray(Info, E, PointeeTy);
9114 return true;
9115}
9116
9117bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9118 if (!IsConstantEvaluatedBuiltinCall(E))
9119 return visitNonBuiltinCallExpr(E);
9120 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9121}
9122
9123// Determine if T is a character type for which we guarantee that
9124// sizeof(T) == 1.
9125static bool isOneByteCharacterType(QualType T) {
9126 return T->isCharType() || T->isChar8Type();
9127}
9128
9129bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9130 unsigned BuiltinOp) {
9131 if (IsNoOpCall(E))
9132 return Success(E);
9133
9134 switch (BuiltinOp) {
9135 case Builtin::BIaddressof:
9136 case Builtin::BI__addressof:
9137 case Builtin::BI__builtin_addressof:
9138 return evaluateLValue(E->getArg(0), Result);
9139 case Builtin::BI__builtin_assume_aligned: {
9140 // We need to be very careful here because: if the pointer does not have the
9141 // asserted alignment, then the behavior is undefined, and undefined
9142 // behavior is non-constant.
9143 if (!evaluatePointer(E->getArg(0), Result))
9144 return false;
9145
9146 LValue OffsetResult(Result);
9147 APSInt Alignment;
9148 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9149 Alignment))
9150 return false;
9151 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9152
9153 if (E->getNumArgs() > 2) {
9154 APSInt Offset;
9155 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9156 return false;
9157
9158 int64_t AdditionalOffset = -Offset.getZExtValue();
9159 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9160 }
9161
9162 // If there is a base object, then it must have the correct alignment.
9163 if (OffsetResult.Base) {
9164 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9165
9166 if (BaseAlignment < Align) {
9167 Result.Designator.setInvalid();
9168 // FIXME: Add support to Diagnostic for long / long long.
9169 CCEDiag(E->getArg(0),
9170 diag::note_constexpr_baa_insufficient_alignment) << 0
9171 << (unsigned)BaseAlignment.getQuantity()
9172 << (unsigned)Align.getQuantity();
9173 return false;
9174 }
9175 }
9176
9177 // The offset must also have the correct alignment.
9178 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9179 Result.Designator.setInvalid();
9180
9181 (OffsetResult.Base
9182 ? CCEDiag(E->getArg(0),
9183 diag::note_constexpr_baa_insufficient_alignment) << 1
9184 : CCEDiag(E->getArg(0),
9185 diag::note_constexpr_baa_value_insufficient_alignment))
9186 << (int)OffsetResult.Offset.getQuantity()
9187 << (unsigned)Align.getQuantity();
9188 return false;
9189 }
9190
9191 return true;
9192 }
9193 case Builtin::BI__builtin_align_up:
9194 case Builtin::BI__builtin_align_down: {
9195 if (!evaluatePointer(E->getArg(0), Result))
9196 return false;
9197 APSInt Alignment;
9198 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9199 Alignment))
9200 return false;
9201 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9202 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9203 // For align_up/align_down, we can return the same value if the alignment
9204 // is known to be greater or equal to the requested value.
9205 if (PtrAlign.getQuantity() >= Alignment)
9206 return true;
9207
9208 // The alignment could be greater than the minimum at run-time, so we cannot
9209 // infer much about the resulting pointer value. One case is possible:
9210 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9211 // can infer the correct index if the requested alignment is smaller than
9212 // the base alignment so we can perform the computation on the offset.
9213 if (BaseAlignment.getQuantity() >= Alignment) {
9214 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", 9215, __extension__ __PRETTY_FUNCTION__
))
9215 "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", 9215, __extension__ __PRETTY_FUNCTION__
))
;
9216 uint64_t Alignment64 = Alignment.getZExtValue();
9217 CharUnits NewOffset = CharUnits::fromQuantity(
9218 BuiltinOp == Builtin::BI__builtin_align_down
9219 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9220 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9221 Result.adjustOffset(NewOffset - Result.Offset);
9222 // TODO: diagnose out-of-bounds values/only allow for arrays?
9223 return true;
9224 }
9225 // Otherwise, we cannot constant-evaluate the result.
9226 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9227 << Alignment;
9228 return false;
9229 }
9230 case Builtin::BI__builtin_operator_new:
9231 return HandleOperatorNewCall(Info, E, Result);
9232 case Builtin::BI__builtin_launder:
9233 return evaluatePointer(E->getArg(0), Result);
9234 case Builtin::BIstrchr:
9235 case Builtin::BIwcschr:
9236 case Builtin::BImemchr:
9237 case Builtin::BIwmemchr:
9238 if (Info.getLangOpts().CPlusPlus11)
9239 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9240 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9241 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9242 else
9243 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9244 [[fallthrough]];
9245 case Builtin::BI__builtin_strchr:
9246 case Builtin::BI__builtin_wcschr:
9247 case Builtin::BI__builtin_memchr:
9248 case Builtin::BI__builtin_char_memchr:
9249 case Builtin::BI__builtin_wmemchr: {
9250 if (!Visit(E->getArg(0)))
9251 return false;
9252 APSInt Desired;
9253 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9254 return false;
9255 uint64_t MaxLength = uint64_t(-1);
9256 if (BuiltinOp != Builtin::BIstrchr &&
9257 BuiltinOp != Builtin::BIwcschr &&
9258 BuiltinOp != Builtin::BI__builtin_strchr &&
9259 BuiltinOp != Builtin::BI__builtin_wcschr) {
9260 APSInt N;
9261 if (!EvaluateInteger(E->getArg(2), N, Info))
9262 return false;
9263 MaxLength = N.getExtValue();
9264 }
9265 // We cannot find the value if there are no candidates to match against.
9266 if (MaxLength == 0u)
9267 return ZeroInitialization(E);
9268 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9269 Result.Designator.Invalid)
9270 return false;
9271 QualType CharTy = Result.Designator.getType(Info.Ctx);
9272 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9273 BuiltinOp == Builtin::BI__builtin_memchr;
9274 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", 9276, __extension__ __PRETTY_FUNCTION__
))
9275 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", 9276, __extension__ __PRETTY_FUNCTION__
))
9276 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", 9276, __extension__ __PRETTY_FUNCTION__
))
;
9277 // Pointers to const void may point to objects of incomplete type.
9278 if (IsRawByte && CharTy->isIncompleteType()) {
9279 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9280 return false;
9281 }
9282 // Give up on byte-oriented matching against multibyte elements.
9283 // FIXME: We can compare the bytes in the correct order.
9284 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9285 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9286 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9287 << CharTy;
9288 return false;
9289 }
9290 // Figure out what value we're actually looking for (after converting to
9291 // the corresponding unsigned type if necessary).
9292 uint64_t DesiredVal;
9293 bool StopAtNull = false;
9294 switch (BuiltinOp) {
9295 case Builtin::BIstrchr:
9296 case Builtin::BI__builtin_strchr:
9297 // strchr compares directly to the passed integer, and therefore
9298 // always fails if given an int that is not a char.
9299 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9300 E->getArg(1)->getType(),
9301 Desired),
9302 Desired))
9303 return ZeroInitialization(E);
9304 StopAtNull = true;
9305 [[fallthrough]];
9306 case Builtin::BImemchr:
9307 case Builtin::BI__builtin_memchr:
9308 case Builtin::BI__builtin_char_memchr:
9309 // memchr compares by converting both sides to unsigned char. That's also
9310 // correct for strchr if we get this far (to cope with plain char being
9311 // unsigned in the strchr case).
9312 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9313 break;
9314
9315 case Builtin::BIwcschr:
9316 case Builtin::BI__builtin_wcschr:
9317 StopAtNull = true;
9318 [[fallthrough]];
9319 case Builtin::BIwmemchr:
9320 case Builtin::BI__builtin_wmemchr:
9321 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9322 DesiredVal = Desired.getZExtValue();
9323 break;
9324 }
9325
9326 for (; MaxLength; --MaxLength) {
9327 APValue Char;
9328 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9329 !Char.isInt())
9330 return false;
9331 if (Char.getInt().getZExtValue() == DesiredVal)
9332 return true;
9333 if (StopAtNull && !Char.getInt())
9334 break;
9335 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9336 return false;
9337 }
9338 // Not found: return nullptr.
9339 return ZeroInitialization(E);
9340 }
9341
9342 case Builtin::BImemcpy:
9343 case Builtin::BImemmove:
9344 case Builtin::BIwmemcpy:
9345 case Builtin::BIwmemmove:
9346 if (Info.getLangOpts().CPlusPlus11)
9347 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9348 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9349 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9350 else
9351 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9352 [[fallthrough]];
9353 case Builtin::BI__builtin_memcpy:
9354 case Builtin::BI__builtin_memmove:
9355 case Builtin::BI__builtin_wmemcpy:
9356 case Builtin::BI__builtin_wmemmove: {
9357 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9358 BuiltinOp == Builtin::BIwmemmove ||
9359 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9360 BuiltinOp == Builtin::BI__builtin_wmemmove;
9361 bool Move = BuiltinOp == Builtin::BImemmove ||
9362 BuiltinOp == Builtin::BIwmemmove ||
9363 BuiltinOp == Builtin::BI__builtin_memmove ||
9364 BuiltinOp == Builtin::BI__builtin_wmemmove;
9365
9366 // The result of mem* is the first argument.
9367 if (!Visit(E->getArg(0)))
9368 return false;
9369 LValue Dest = Result;
9370
9371 LValue Src;
9372 if (!EvaluatePointer(E->getArg(1), Src, Info))
9373 return false;
9374
9375 APSInt N;
9376 if (!EvaluateInteger(E->getArg(2), N, Info))
9377 return false;
9378 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", 9378, __extension__ __PRETTY_FUNCTION__
))
;
9379
9380 // If the size is zero, we treat this as always being a valid no-op.
9381 // (Even if one of the src and dest pointers is null.)
9382 if (!N)
9383 return true;
9384
9385 // Otherwise, if either of the operands is null, we can't proceed. Don't
9386 // try to determine the type of the copied objects, because there aren't
9387 // any.
9388 if (!Src.Base || !Dest.Base) {
9389 APValue Val;
9390 (!Src.Base ? Src : Dest).moveInto(Val);
9391 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9392 << Move << WChar << !!Src.Base
9393 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9394 return false;
9395 }
9396 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9397 return false;
9398
9399 // We require that Src and Dest are both pointers to arrays of
9400 // trivially-copyable type. (For the wide version, the designator will be
9401 // invalid if the designated object is not a wchar_t.)
9402 QualType T = Dest.Designator.getType(Info.Ctx);
9403 QualType SrcT = Src.Designator.getType(Info.Ctx);
9404 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9405 // FIXME: Consider using our bit_cast implementation to support this.
9406 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9407 return false;
9408 }
9409 if (T->isIncompleteType()) {
9410 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9411 return false;
9412 }
9413 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9414 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9415 return false;
9416 }
9417
9418 // Figure out how many T's we're copying.
9419 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9420 if (!WChar) {
9421 uint64_t Remainder;
9422 llvm::APInt OrigN = N;
9423 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9424 if (Remainder) {
9425 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9426 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9427 << (unsigned)TSize;
9428 return false;
9429 }
9430 }
9431
9432 // Check that the copying will remain within the arrays, just so that we
9433 // can give a more meaningful diagnostic. This implicitly also checks that
9434 // N fits into 64 bits.
9435 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9436 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9437 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9438 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9439 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9440 << toString(N, 10, /*Signed*/false);
9441 return false;
9442 }
9443 uint64_t NElems = N.getZExtValue();
9444 uint64_t NBytes = NElems * TSize;
9445
9446 // Check for overlap.
9447 int Direction = 1;
9448 if (HasSameBase(Src, Dest)) {
9449 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9450 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9451 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9452 // Dest is inside the source region.
9453 if (!Move) {
9454 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9455 return false;
9456 }
9457 // For memmove and friends, copy backwards.
9458 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9459 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9460 return false;
9461 Direction = -1;
9462 } else if (!Move && SrcOffset >= DestOffset &&
9463 SrcOffset - DestOffset < NBytes) {
9464 // Src is inside the destination region for memcpy: invalid.
9465 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9466 return false;
9467 }
9468 }
9469
9470 while (true) {
9471 APValue Val;
9472 // FIXME: Set WantObjectRepresentation to true if we're copying a
9473 // char-like type?
9474 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9475 !handleAssignment(Info, E, Dest, T, Val))
9476 return false;
9477 // Do not iterate past the last element; if we're copying backwards, that
9478 // might take us off the start of the array.
9479 if (--NElems == 0)
9480 return true;
9481 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9482 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9483 return false;
9484 }
9485 }
9486
9487 default:
9488 return false;
9489 }
9490}
9491
9492static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9493 APValue &Result, const InitListExpr *ILE,
9494 QualType AllocType);
9495static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9496 APValue &Result,
9497 const CXXConstructExpr *CCE,
9498 QualType AllocType);
9499
9500bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9501 if (!Info.getLangOpts().CPlusPlus20)
9502 Info.CCEDiag(E, diag::note_constexpr_new);
9503
9504 // We cannot speculatively evaluate a delete expression.
9505 if (Info.SpeculativeEvaluationDepth)
9506 return false;
9507
9508 FunctionDecl *OperatorNew = E->getOperatorNew();
9509
9510 bool IsNothrow = false;
9511 bool IsPlacement = false;
9512 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9513 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9514 // FIXME Support array placement new.
9515 assert(E->getNumPlacementArgs() == 1)(static_cast <bool> (E->getNumPlacementArgs() == 1) ?
void (0) : __assert_fail ("E->getNumPlacementArgs() == 1"
, "clang/lib/AST/ExprConstant.cpp", 9515, __extension__ __PRETTY_FUNCTION__
))
;
9516 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9517 return false;
9518 if (Result.Designator.Invalid)
9519 return false;
9520 IsPlacement = true;
9521 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9522 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9523 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9524 return false;
9525 } else if (E->getNumPlacementArgs()) {
9526 // The only new-placement list we support is of the form (std::nothrow).
9527 //
9528 // FIXME: There is no restriction on this, but it's not clear that any
9529 // other form makes any sense. We get here for cases such as:
9530 //
9531 // new (std::align_val_t{N}) X(int)
9532 //
9533 // (which should presumably be valid only if N is a multiple of
9534 // alignof(int), and in any case can't be deallocated unless N is
9535 // alignof(X) and X has new-extended alignment).
9536 if (E->getNumPlacementArgs() != 1 ||
9537 !E->getPlacementArg(0)->getType()->isNothrowT())
9538 return Error(E, diag::note_constexpr_new_placement);
9539
9540 LValue Nothrow;
9541 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9542 return false;
9543 IsNothrow = true;
9544 }
9545
9546 const Expr *Init = E->getInitializer();
9547 const InitListExpr *ResizedArrayILE = nullptr;
9548 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9549 bool ValueInit = false;
9550
9551 QualType AllocType = E->getAllocatedType();
9552 if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9553 const Expr *Stripped = *ArraySize;
9554 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9555 Stripped = ICE->getSubExpr())
9556 if (ICE->getCastKind() != CK_NoOp &&
9557 ICE->getCastKind() != CK_IntegralCast)
9558 break;
9559
9560 llvm::APSInt ArrayBound;
9561 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9562 return false;
9563
9564 // C++ [expr.new]p9:
9565 // The expression is erroneous if:
9566 // -- [...] its value before converting to size_t [or] applying the
9567 // second standard conversion sequence is less than zero
9568 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9569 if (IsNothrow)
9570 return ZeroInitialization(E);
9571
9572 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9573 << ArrayBound << (*ArraySize)->getSourceRange();
9574 return false;
9575 }
9576
9577 // -- its value is such that the size of the allocated object would
9578 // exceed the implementation-defined limit
9579 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9580 ArrayBound) >
9581 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9582 if (IsNothrow)
9583 return ZeroInitialization(E);
9584
9585 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9586 << ArrayBound << (*ArraySize)->getSourceRange();
9587 return false;
9588 }
9589
9590 // -- the new-initializer is a braced-init-list and the number of
9591 // array elements for which initializers are provided [...]
9592 // exceeds the number of elements to initialize
9593 if (!Init) {
9594 // No initialization is performed.
9595 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9596 isa<ImplicitValueInitExpr>(Init)) {
9597 ValueInit = true;
9598 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9599 ResizedArrayCCE = CCE;
9600 } else {
9601 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9602 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", 9602, __extension__ __PRETTY_FUNCTION__
))
;
9603
9604 unsigned Bits =
9605 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9606 llvm::APInt InitBound = CAT->getSize().zext(Bits);
9607 llvm::APInt AllocBound = ArrayBound.zext(Bits);
9608 if (InitBound.ugt(AllocBound)) {
9609 if (IsNothrow)
9610 return ZeroInitialization(E);
9611
9612 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9613 << toString(AllocBound, 10, /*Signed=*/false)
9614 << toString(InitBound, 10, /*Signed=*/false)
9615 << (*ArraySize)->getSourceRange();
9616 return false;
9617 }
9618
9619 // If the sizes differ, we must have an initializer list, and we need
9620 // special handling for this case when we initialize.
9621 if (InitBound != AllocBound)
9622 ResizedArrayILE = cast<InitListExpr>(Init);
9623 }
9624
9625 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9626 ArrayType::Normal, 0);
9627 } else {
9628 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", 9629, __extension__ __PRETTY_FUNCTION__
))
9629 "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", 9629, __extension__ __PRETTY_FUNCTION__
))
;
9630 }
9631
9632 APValue *Val;
9633 if (IsPlacement) {
9634 AccessKinds AK = AK_Construct;
9635 struct FindObjectHandler {
9636 EvalInfo &Info;
9637 const Expr *E;
9638 QualType AllocType;
9639 const AccessKinds AccessKind;
9640 APValue *Value;
9641
9642 typedef bool result_type;
9643 bool failed() { return false; }
9644 bool found(APValue &Subobj, QualType SubobjType) {
9645 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9646 // old name of the object to be used to name the new object.
9647 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9648 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9649 SubobjType << AllocType;
9650 return false;
9651 }
9652 Value = &Subobj;
9653 return true;
9654 }
9655 bool found(APSInt &Value, QualType SubobjType) {
9656 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9657 return false;
9658 }
9659 bool found(APFloat &Value, QualType SubobjType) {
9660 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9661 return false;
9662 }
9663 } Handler = {Info, E, AllocType, AK, nullptr};
9664
9665 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9666 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9667 return false;
9668
9669 Val = Handler.Value;
9670
9671 // [basic.life]p1:
9672 // The lifetime of an object o of type T ends when [...] the storage
9673 // which the object occupies is [...] reused by an object that is not
9674 // nested within o (6.6.2).
9675 *Val = APValue();
9676 } else {
9677 // Perform the allocation and obtain a pointer to the resulting object.
9678 Val = Info.createHeapAlloc(E, AllocType, Result);
9679 if (!Val)
9680 return false;
9681 }
9682
9683 if (ValueInit) {
9684 ImplicitValueInitExpr VIE(AllocType);
9685 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9686 return false;
9687 } else if (ResizedArrayILE) {
9688 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9689 AllocType))
9690 return false;
9691 } else if (ResizedArrayCCE) {
9692 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9693 AllocType))
9694 return false;
9695 } else if (Init) {
9696 if (!EvaluateInPlace(*Val, Info, Result, Init))
9697 return false;
9698 } else if (!getDefaultInitValue(AllocType, *Val)) {
9699 return false;
9700 }
9701
9702 // Array new returns a pointer to the first element, not a pointer to the
9703 // array.
9704 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9705 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9706
9707 return true;
9708}
9709//===----------------------------------------------------------------------===//
9710// Member Pointer Evaluation
9711//===----------------------------------------------------------------------===//
9712
9713namespace {
9714class MemberPointerExprEvaluator
9715 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9716 MemberPtr &Result;
9717
9718 bool Success(const ValueDecl *D) {
9719 Result = MemberPtr(D);
9720 return true;
9721 }
9722public:
9723
9724 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9725 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9726
9727 bool Success(const APValue &V, const Expr *E) {
9728 Result.setFrom(V);
9729 return true;
9730 }
9731 bool ZeroInitialization(const Expr *E) {
9732 return Success((const ValueDecl*)nullptr);
9733 }
9734
9735 bool VisitCastExpr(const CastExpr *E);
9736 bool VisitUnaryAddrOf(const UnaryOperator *E);
9737};
9738} // end anonymous namespace
9739
9740static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9741 EvalInfo &Info) {
9742 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 9742, __extension__ __PRETTY_FUNCTION__))
;
9743 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", 9743, __extension__ __PRETTY_FUNCTION__
))
;
9744 return MemberPointerExprEvaluator(Info, Result).Visit(E);
9745}
9746
9747bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9748 switch (E->getCastKind()) {
9749 default:
9750 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9751
9752 case CK_NullToMemberPointer:
9753 VisitIgnoredValue(E->getSubExpr());
9754 return ZeroInitialization(E);
9755
9756 case CK_BaseToDerivedMemberPointer: {
9757 if (!Visit(E->getSubExpr()))
9758 return false;
9759 if (E->path_empty())
9760 return true;
9761 // Base-to-derived member pointer casts store the path in derived-to-base
9762 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9763 // the wrong end of the derived->base arc, so stagger the path by one class.
9764 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9765 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9766 PathI != PathE; ++PathI) {
9767 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", 9767, __extension__ __PRETTY_FUNCTION__
))
;
9768 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9769 if (!Result.castToDerived(Derived))
9770 return Error(E);
9771 }
9772 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9773 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9774 return Error(E);
9775 return true;
9776 }
9777
9778 case CK_DerivedToBaseMemberPointer:
9779 if (!Visit(E->getSubExpr()))
9780 return false;
9781 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9782 PathE = E->path_end(); PathI != PathE; ++PathI) {
9783 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", 9783, __extension__ __PRETTY_FUNCTION__
))
;
9784 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9785 if (!Result.castToBase(Base))
9786 return Error(E);
9787 }
9788 return true;
9789 }
9790}
9791
9792bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9793 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9794 // member can be formed.
9795 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9796}
9797
9798//===----------------------------------------------------------------------===//
9799// Record Evaluation
9800//===----------------------------------------------------------------------===//
9801
9802namespace {
9803 class RecordExprEvaluator
9804 : public ExprEvaluatorBase<RecordExprEvaluator> {
9805 const LValue &This;
9806 APValue &Result;
9807 public:
9808
9809 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9810 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9811
9812 bool Success(const APValue &V, const Expr *E) {
9813 Result = V;
9814 return true;
9815 }
9816 bool ZeroInitialization(const Expr *E) {
9817 return ZeroInitialization(E, E->getType());
9818 }
9819 bool ZeroInitialization(const Expr *E, QualType T);
9820
9821 bool VisitCallExpr(const CallExpr *E) {
9822 return handleCallExpr(E, Result, &This);
9823 }
9824 bool VisitCastExpr(const CastExpr *E);
9825 bool VisitInitListExpr(const InitListExpr *E);
9826 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9827 return VisitCXXConstructExpr(E, E->getType());
9828 }
9829 bool VisitLambdaExpr(const LambdaExpr *E);
9830 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9831 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9832 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9833 bool VisitBinCmp(const BinaryOperator *E);
9834 };
9835}
9836
9837/// Perform zero-initialization on an object of non-union class type.
9838/// C++11 [dcl.init]p5:
9839/// To zero-initialize an object or reference of type T means:
9840/// [...]
9841/// -- if T is a (possibly cv-qualified) non-union class type,
9842/// each non-static data member and each base-class subobject is
9843/// zero-initialized
9844static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9845 const RecordDecl *RD,
9846 const LValue &This, APValue &Result) {
9847 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", 9847, __extension__ __PRETTY_FUNCTION__
))
;
9848 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9849 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9850 std::distance(RD->field_begin(), RD->field_end()));
9851
9852 if (RD->isInvalidDecl()) return false;
9853 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9854
9855 if (CD) {
9856 unsigned Index = 0;
9857 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9858 End = CD->bases_end(); I != End; ++I, ++Index) {
9859 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9860 LValue Subobject = This;
9861 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9862 return false;
9863 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9864 Result.getStructBase(Index)))
9865 return false;
9866 }
9867 }
9868
9869 for (const auto *I : RD->fields()) {
9870 // -- if T is a reference type, no initialization is performed.
9871 if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9872 continue;
9873
9874 LValue Subobject = This;
9875 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9876 return false;
9877
9878 ImplicitValueInitExpr VIE(I->getType());
9879 if (!EvaluateInPlace(
9880 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9881 return false;
9882 }
9883
9884 return true;
9885}
9886
9887bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9888 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9889 if (RD->isInvalidDecl()) return false;
9890 if (RD->isUnion()) {
9891 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9892 // object's first non-static named data member is zero-initialized
9893 RecordDecl::field_iterator I = RD->field_begin();
9894 while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9895 ++I;
9896 if (I == RD->field_end()) {
9897 Result = APValue((const FieldDecl*)nullptr);
9898 return true;
9899 }
9900
9901 LValue Subobject = This;
9902 if (!HandleLValueMember(Info, E, Subobject, *I))
9903 return false;
9904 Result = APValue(*I);
9905 ImplicitValueInitExpr VIE(I->getType());
9906 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9907 }
9908
9909 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9910 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9911 return false;
9912 }
9913
9914 return HandleClassZeroInitialization(Info, E, RD, This, Result);
9915}
9916
9917bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9918 switch (E->getCastKind()) {
9919 default:
9920 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9921
9922 case CK_ConstructorConversion:
9923 return Visit(E->getSubExpr());
9924
9925 case CK_DerivedToBase:
9926 case CK_UncheckedDerivedToBase: {
9927 APValue DerivedObject;
9928 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9929 return false;
9930 if (!DerivedObject.isStruct())
9931 return Error(E->getSubExpr());
9932
9933 // Derived-to-base rvalue conversion: just slice off the derived part.
9934 APValue *Value = &DerivedObject;
9935 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9936 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9937 PathE = E->path_end(); PathI != PathE; ++PathI) {
9938 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", 9938, __extension__ __PRETTY_FUNCTION__
))
;
9939 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9940 Value = &Value->getStructBase(getBaseIndex(RD, Base));
9941 RD = Base;
9942 }
9943 Result = *Value;
9944 return true;
9945 }
9946 }
9947}
9948
9949bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9950 if (E->isTransparent())
9951 return Visit(E->getInit(0));
9952
9953 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9954 if (RD->isInvalidDecl()) return false;
9955 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9956 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9957
9958 EvalInfo::EvaluatingConstructorRAII EvalObj(
9959 Info,
9960 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9961 CXXRD && CXXRD->getNumBases());
9962
9963 if (RD->isUnion()) {
9964 const FieldDecl *Field = E->getInitializedFieldInUnion();
9965 Result = APValue(Field);
9966 if (!Field)
9967 return true;
9968
9969 // If the initializer list for a union does not contain any elements, the
9970 // first element of the union is value-initialized.
9971 // FIXME: The element should be initialized from an initializer list.
9972 // Is this difference ever observable for initializer lists which
9973 // we don't build?
9974 ImplicitValueInitExpr VIE(Field->getType());
9975 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9976
9977 LValue Subobject = This;
9978 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9979 return false;
9980
9981 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9982 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9983 isa<CXXDefaultInitExpr>(InitExpr));
9984
9985 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9986 if (Field->isBitField())
9987 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9988 Field);
9989 return true;
9990 }
9991
9992 return false;
9993 }
9994
9995 if (!Result.hasValue())
9996 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9997 std::distance(RD->field_begin(), RD->field_end()));
9998 unsigned ElementNo = 0;
9999 bool Success = true;
10000
10001 // Initialize base classes.
10002 if (CXXRD && CXXRD->getNumBases()) {
10003 for (const auto &Base : CXXRD->bases()) {
10004 assert(ElementNo < E->getNumInits() && "missing init for base class")(static_cast <bool> (ElementNo < E->getNumInits()
&& "missing init for base class") ? void (0) : __assert_fail
("ElementNo < E->getNumInits() && \"missing init for base class\""
, "clang/lib/AST/ExprConstant.cpp", 10004, __extension__ __PRETTY_FUNCTION__
))
;
10005 const Expr *Init = E->getInit(ElementNo);
10006
10007 LValue Subobject = This;
10008 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10009 return false;
10010
10011 APValue &FieldVal = Result.getStructBase(ElementNo);
10012 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10013 if (!Info.noteFailure())
10014 return false;
10015 Success = false;
10016 }
10017 ++ElementNo;
10018 }
10019
10020 EvalObj.finishedConstructingBases();
10021 }
10022
10023 // Initialize members.
10024 for (const auto *Field : RD->fields()) {
10025 // Anonymous bit-fields are not considered members of the class for
10026 // purposes of aggregate initialization.
10027 if (Field->isUnnamedBitfield())
10028 continue;
10029
10030 LValue Subobject = This;
10031
10032 bool HaveInit = ElementNo < E->getNumInits();
10033
10034 // FIXME: Diagnostics here should point to the end of the initializer
10035 // list, not the start.
10036 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10037 Subobject, Field, &Layout))
10038 return false;
10039
10040 // Perform an implicit value-initialization for members beyond the end of
10041 // the initializer list.
10042 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10043 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10044
10045 if (Field->getType()->isIncompleteArrayType()) {
10046 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10047 if (!CAT->getSize().isZero()) {
10048 // Bail out for now. This might sort of "work", but the rest of the
10049 // code isn't really prepared to handle it.
10050 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10051 return false;
10052 }
10053 }
10054 }
10055
10056 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10057 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10058 isa<CXXDefaultInitExpr>(Init));
10059
10060 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10061 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10062 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10063 FieldVal, Field))) {
10064 if (!Info.noteFailure())
10065 return false;
10066 Success = false;
10067 }
10068 }
10069
10070 EvalObj.finishedConstructingFields();
10071
10072 return Success;
10073}
10074
10075bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10076 QualType T) {
10077 // Note that E's type is not necessarily the type of our class here; we might
10078 // be initializing an array element instead.
10079 const CXXConstructorDecl *FD = E->getConstructor();
10080 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10081
10082 bool ZeroInit = E->requiresZeroInitialization();
10083 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10084 // If we've already performed zero-initialization, we're already done.
10085 if (Result.hasValue())
10086 return true;
10087
10088 if (ZeroInit)
10089 return ZeroInitialization(E, T);
10090
10091 return getDefaultInitValue(T, Result);
10092 }
10093
10094 const FunctionDecl *Definition = nullptr;
10095 auto Body = FD->getBody(Definition);
10096
10097 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10098 return false;
10099
10100 // Avoid materializing a temporary for an elidable copy/move constructor.
10101 if (E->isElidable() && !ZeroInit) {
10102 // FIXME: This only handles the simplest case, where the source object
10103 // is passed directly as the first argument to the constructor.
10104 // This should also handle stepping though implicit casts and
10105 // and conversion sequences which involve two steps, with a
10106 // conversion operator followed by a converting constructor.
10107 const Expr *SrcObj = E->getArg(0);
10108 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", 10108, __extension__ __PRETTY_FUNCTION__
))
;
10109 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", 10109, __extension__ __PRETTY_FUNCTION__
))
;
10110 if (const MaterializeTemporaryExpr *ME =
10111 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10112 return Visit(ME->getSubExpr());
10113 }
10114
10115 if (ZeroInit && !ZeroInitialization(E, T))
10116 return false;
10117
10118 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10119 return HandleConstructorCall(E, This, Args,
10120 cast<CXXConstructorDecl>(Definition), Info,
10121 Result);
10122}
10123
10124bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10125 const CXXInheritedCtorInitExpr *E) {
10126 if (!Info.CurrentCall) {
10127 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "clang/lib/AST/ExprConstant.cpp", 10127, __extension__ __PRETTY_FUNCTION__
))
;
10128 return false;
10129 }
10130
10131 const CXXConstructorDecl *FD = E->getConstructor();
10132 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10133 return false;
10134
10135 const FunctionDecl *Definition = nullptr;
10136 auto Body = FD->getBody(Definition);
10137
10138 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10139 return false;
10140
10141 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10142 cast<CXXConstructorDecl>(Definition), Info,
10143 Result);
10144}
10145
10146bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10147 const CXXStdInitializerListExpr *E) {
10148 const ConstantArrayType *ArrayType =
10149 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10150
10151 LValue Array;
10152 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10153 return false;
10154
10155 // Get a pointer to the first element of the array.
10156 Array.addArray(Info, E, ArrayType);
10157
10158 auto InvalidType = [&] {
10159 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10160 << E->getType();
10161 return false;
10162 };
10163
10164 // FIXME: Perform the checks on the field types in SemaInit.
10165 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10166 RecordDecl::field_iterator Field = Record->field_begin();
10167 if (Field == Record->field_end())
10168 return InvalidType();
10169
10170 // Start pointer.
10171 if (!Field->getType()->isPointerType() ||
10172 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10173 ArrayType->getElementType()))
10174 return InvalidType();
10175
10176 // FIXME: What if the initializer_list type has base classes, etc?
10177 Result = APValue(APValue::UninitStruct(), 0, 2);
10178 Array.moveInto(Result.getStructField(0));
10179
10180 if (++Field == Record->field_end())
10181 return InvalidType();
10182
10183 if (Field->getType()->isPointerType() &&
10184 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10185 ArrayType->getElementType())) {
10186 // End pointer.
10187 if (!HandleLValueArrayAdjustment(Info, E, Array,
10188 ArrayType->getElementType(),
10189 ArrayType->getSize().getZExtValue()))
10190 return false;
10191 Array.moveInto(Result.getStructField(1));
10192 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10193 // Length.
10194 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10195 else
10196 return InvalidType();
10197
10198 if (++Field != Record->field_end())
10199 return InvalidType();
10200
10201 return true;
10202}
10203
10204bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10205 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10206 if (ClosureClass->isInvalidDecl())
10207 return false;
10208
10209 const size_t NumFields =
10210 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10211
10212 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", 10215, __extension__ __PRETTY_FUNCTION__
))
10213 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", 10215, __extension__ __PRETTY_FUNCTION__
))
10214 "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", 10215, __extension__ __PRETTY_FUNCTION__
))
10215 "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", 10215, __extension__ __PRETTY_FUNCTION__
))
;
10216
10217 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10218 // Iterate through all the lambda's closure object's fields and initialize
10219 // them.
10220 auto *CaptureInitIt = E->capture_init_begin();
10221 bool Success = true;
10222 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10223 for (const auto *Field : ClosureClass->fields()) {
10224 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", 10224, __extension__ __PRETTY_FUNCTION__
))
;
10225 // Get the initializer for this field
10226 Expr *const CurFieldInit = *CaptureInitIt++;
10227
10228 // If there is no initializer, either this is a VLA or an error has
10229 // occurred.
10230 if (!CurFieldInit)
10231 return Error(E);
10232
10233 LValue Subobject = This;
10234
10235 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10236 return false;
10237
10238 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10239 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10240 if (!Info.keepEvaluatingAfterFailure())
10241 return false;
10242 Success = false;
10243 }
10244 }
10245 return Success;
10246}
10247
10248static bool EvaluateRecord(const Expr *E, const LValue &This,
10249 APValue &Result, EvalInfo &Info) {
10250 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10250, __extension__ __PRETTY_FUNCTION__))
;
10251 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", 10252, __extension__ __PRETTY_FUNCTION__
))
10252 "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", 10252, __extension__ __PRETTY_FUNCTION__
))
;
10253 return RecordExprEvaluator(Info, This, Result).Visit(E);
10254}
10255
10256//===----------------------------------------------------------------------===//
10257// Temporary Evaluation
10258//
10259// Temporaries are represented in the AST as rvalues, but generally behave like
10260// lvalues. The full-object of which the temporary is a subobject is implicitly
10261// materialized so that a reference can bind to it.
10262//===----------------------------------------------------------------------===//
10263namespace {
10264class TemporaryExprEvaluator
10265 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10266public:
10267 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10268 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10269
10270 /// Visit an expression which constructs the value of this temporary.
10271 bool VisitConstructExpr(const Expr *E) {
10272 APValue &Value = Info.CurrentCall->createTemporary(
10273 E, E->getType(), ScopeKind::FullExpression, Result);
10274 return EvaluateInPlace(Value, Info, Result, E);
10275 }
10276
10277 bool VisitCastExpr(const CastExpr *E) {
10278 switch (E->getCastKind()) {
10279 default:
10280 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10281
10282 case CK_ConstructorConversion:
10283 return VisitConstructExpr(E->getSubExpr());
10284 }
10285 }
10286 bool VisitInitListExpr(const InitListExpr *E) {
10287 return VisitConstructExpr(E);
10288 }
10289 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10290 return VisitConstructExpr(E);
10291 }
10292 bool VisitCallExpr(const CallExpr *E) {
10293 return VisitConstructExpr(E);
10294 }
10295 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10296 return VisitConstructExpr(E);
10297 }
10298 bool VisitLambdaExpr(const LambdaExpr *E) {
10299 return VisitConstructExpr(E);
10300 }
10301};
10302} // end anonymous namespace
10303
10304/// Evaluate an expression of record type as a temporary.
10305static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10306 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10306, __extension__ __PRETTY_FUNCTION__))
;
10307 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", 10307, __extension__ __PRETTY_FUNCTION__
))
;
10308 return TemporaryExprEvaluator(Info, Result).Visit(E);
10309}
10310
10311//===----------------------------------------------------------------------===//
10312// Vector Evaluation
10313//===----------------------------------------------------------------------===//
10314
10315namespace {
10316 class VectorExprEvaluator
10317 : public ExprEvaluatorBase<VectorExprEvaluator> {
10318 APValue &Result;
10319 public:
10320
10321 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10322 : ExprEvaluatorBaseTy(info), Result(Result) {}
10323
10324 bool Success(ArrayRef<APValue> V, const Expr *E) {
10325 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", 10325, __extension__ __PRETTY_FUNCTION__
))
;
10326 // FIXME: remove this APValue copy.
10327 Result = APValue(V.data(), V.size());
10328 return true;
10329 }
10330 bool Success(const APValue &V, const Expr *E) {
10331 assert(V.isVector())(static_cast <bool> (V.isVector()) ? void (0) : __assert_fail
("V.isVector()", "clang/lib/AST/ExprConstant.cpp", 10331, __extension__
__PRETTY_FUNCTION__))
;
10332 Result = V;
10333 return true;
10334 }
10335 bool ZeroInitialization(const Expr *E);
10336
10337 bool VisitUnaryReal(const UnaryOperator *E)
10338 { return Visit(E->getSubExpr()); }
10339 bool VisitCastExpr(const CastExpr* E);
10340 bool VisitInitListExpr(const InitListExpr *E);
10341 bool VisitUnaryImag(const UnaryOperator *E);
10342 bool VisitBinaryOperator(const BinaryOperator *E);
10343 bool VisitUnaryOperator(const UnaryOperator *E);
10344 // FIXME: Missing: conditional operator (for GNU
10345 // conditional select), shufflevector, ExtVectorElementExpr
10346 };
10347} // end anonymous namespace
10348
10349static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10350 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", 10351, __extension__ __PRETTY_FUNCTION__
))
10351 "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", 10351, __extension__ __PRETTY_FUNCTION__
))
;
10352 return VectorExprEvaluator(Info, Result).Visit(E);
10353}
10354
10355bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10356 const VectorType *VTy = E->getType()->castAs<VectorType>();
10357 unsigned NElts = VTy->getNumElements();
10358
10359 const Expr *SE = E->getSubExpr();
10360 QualType SETy = SE->getType();
10361
10362 switch (E->getCastKind()) {
10363 case CK_VectorSplat: {
10364 APValue Val = APValue();
10365 if (SETy->isIntegerType()) {
10366 APSInt IntResult;
10367 if (!EvaluateInteger(SE, IntResult, Info))
10368 return false;
10369 Val = APValue(std::move(IntResult));
10370 } else if (SETy->isRealFloatingType()) {
10371 APFloat FloatResult(0.0);
10372 if (!EvaluateFloat(SE, FloatResult, Info))
10373 return false;
10374 Val = APValue(std::move(FloatResult));
10375 } else {
10376 return Error(E);
10377 }
10378
10379 // Splat and create vector APValue.
10380 SmallVector<APValue, 4> Elts(NElts, Val);
10381 return Success(Elts, E);
10382 }
10383 case CK_BitCast: {
10384 // Evaluate the operand into an APInt we can extract from.
10385 llvm::APInt SValInt;
10386 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10387 return false;
10388 // Extract the elements
10389 QualType EltTy = VTy->getElementType();
10390 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10391 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10392 SmallVector<APValue, 4> Elts;
10393 if (EltTy->isRealFloatingType()) {
10394 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10395 unsigned FloatEltSize = EltSize;
10396 if (&Sem == &APFloat::x87DoubleExtended())
10397 FloatEltSize = 80;
10398 for (unsigned i = 0; i < NElts; i++) {
10399 llvm::APInt Elt;
10400 if (BigEndian)
10401 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10402 else
10403 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10404 Elts.push_back(APValue(APFloat(Sem, Elt)));
10405 }
10406 } else if (EltTy->isIntegerType()) {
10407 for (unsigned i = 0; i < NElts; i++) {
10408 llvm::APInt Elt;
10409 if (BigEndian)
10410 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10411 else
10412 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10413 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10414 }
10415 } else {
10416 return Error(E);
10417 }
10418 return Success(Elts, E);
10419 }
10420 default:
10421 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10422 }
10423}
10424
10425bool
10426VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10427 const VectorType *VT = E->getType()->castAs<VectorType>();
10428 unsigned NumInits = E->getNumInits();
10429 unsigned NumElements = VT->getNumElements();
10430
10431 QualType EltTy = VT->getElementType();
10432 SmallVector<APValue, 4> Elements;
10433
10434 // The number of initializers can be less than the number of
10435 // vector elements. For OpenCL, this can be due to nested vector
10436 // initialization. For GCC compatibility, missing trailing elements
10437 // should be initialized with zeroes.
10438 unsigned CountInits = 0, CountElts = 0;
10439 while (CountElts < NumElements) {
10440 // Handle nested vector initialization.
10441 if (CountInits < NumInits
10442 && E->getInit(CountInits)->getType()->isVectorType()) {
10443 APValue v;
10444 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10445 return Error(E);
10446 unsigned vlen = v.getVectorLength();
10447 for (unsigned j = 0; j < vlen; j++)
10448 Elements.push_back(v.getVectorElt(j));
10449 CountElts += vlen;
10450 } else if (EltTy->isIntegerType()) {
10451 llvm::APSInt sInt(32);
10452 if (CountInits < NumInits) {
10453 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10454 return false;
10455 } else // trailing integer zero.
10456 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10457 Elements.push_back(APValue(sInt));
10458 CountElts++;
10459 } else {
10460 llvm::APFloat f(0.0);
10461 if (CountInits < NumInits) {
10462 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10463 return false;
10464 } else // trailing float zero.
10465 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10466 Elements.push_back(APValue(f));
10467 CountElts++;
10468 }
10469 CountInits++;
10470 }
10471 return Success(Elements, E);
10472}
10473
10474bool
10475VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10476 const auto *VT = E->getType()->castAs<VectorType>();
10477 QualType EltTy = VT->getElementType();
10478 APValue ZeroElement;
10479 if (EltTy->isIntegerType())
10480 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10481 else
10482 ZeroElement =
10483 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10484
10485 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10486 return Success(Elements, E);
10487}
10488
10489bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10490 VisitIgnoredValue(E->getSubExpr());
10491 return ZeroInitialization(E);
10492}
10493
10494bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10495 BinaryOperatorKind Op = E->getOpcode();
10496 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", 10497, __extension__ __PRETTY_FUNCTION__
))
10497 "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", 10497, __extension__ __PRETTY_FUNCTION__
))
;
10498
10499 if (Op == BO_Comma)
10500 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10501
10502 Expr *LHS = E->getLHS();
10503 Expr *RHS = E->getRHS();
10504
10505 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", 10506, __extension__ __PRETTY_FUNCTION__
))
10506 "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", 10506, __extension__ __PRETTY_FUNCTION__
))
;
10507 // Checking JUST the types are the same would be fine, except shifts don't
10508 // need to have their types be the same (since you always shift by an int).
10509 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", 10513, __extension__ __PRETTY_FUNCTION__
))
10510 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", 10513, __extension__ __PRETTY_FUNCTION__
))
10511 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", 10513, __extension__ __PRETTY_FUNCTION__
))
10512 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", 10513, __extension__ __PRETTY_FUNCTION__
))
10513 "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", 10513, __extension__ __PRETTY_FUNCTION__
))
;
10514
10515 APValue LHSValue;
10516 APValue RHSValue;
10517 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10518 if (!LHSOK && !Info.noteFailure())
10519 return false;
10520 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10521 return false;
10522
10523 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10524 return false;
10525
10526 return Success(LHSValue, E);
10527}
10528
10529static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10530 QualType ResultTy,
10531 UnaryOperatorKind Op,
10532 APValue Elt) {
10533 switch (Op) {
10534 case UO_Plus:
10535 // Nothing to do here.
10536 return Elt;
10537 case UO_Minus:
10538 if (Elt.getKind() == APValue::Int) {
10539 Elt.getInt().negate();
10540 } else {
10541 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", 10542, __extension__ __PRETTY_FUNCTION__
))
10542 "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", 10542, __extension__ __PRETTY_FUNCTION__
))
;
10543 Elt.getFloat().changeSign();
10544 }
10545 return Elt;
10546 case UO_Not:
10547 // This is only valid for integral types anyway, so we don't have to handle
10548 // float here.
10549 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", 10550, __extension__ __PRETTY_FUNCTION__
))
10550 "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", 10550, __extension__ __PRETTY_FUNCTION__
))
;
10551 Elt.getInt().flipAllBits();
10552 return Elt;
10553 case UO_LNot: {
10554 if (Elt.getKind() == APValue::Int) {
10555 Elt.getInt() = !Elt.getInt();
10556 // operator ! on vectors returns -1 for 'truth', so negate it.
10557 Elt.getInt().negate();
10558 return Elt;
10559 }
10560 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", 10561, __extension__ __PRETTY_FUNCTION__
))
10561 "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", 10561, __extension__ __PRETTY_FUNCTION__
))
;
10562 // Float types result in an int of the same size, but -1 for true, or 0 for
10563 // false.
10564 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10565 ResultTy->isUnsignedIntegerType()};
10566 if (Elt.getFloat().isZero())
10567 EltResult.setAllBits();
10568 else
10569 EltResult.clearAllBits();
10570
10571 return APValue{EltResult};
10572 }
10573 default:
10574 // FIXME: Implement the rest of the unary operators.
10575 return std::nullopt;
10576 }
10577}
10578
10579bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10580 Expr *SubExpr = E->getSubExpr();
10581 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10582 // This result element type differs in the case of negating a floating point
10583 // vector, since the result type is the a vector of the equivilant sized
10584 // integer.
10585 const QualType ResultEltTy = VD->getElementType();
10586 UnaryOperatorKind Op = E->getOpcode();
10587
10588 APValue SubExprValue;
10589 if (!Evaluate(SubExprValue, Info, SubExpr))
10590 return false;
10591
10592 // FIXME: This vector evaluator someday needs to be changed to be LValue
10593 // aware/keep LValue information around, rather than dealing with just vector
10594 // types directly. Until then, we cannot handle cases where the operand to
10595 // these unary operators is an LValue. The only case I've been able to see
10596 // cause this is operator++ assigning to a member expression (only valid in
10597 // altivec compilations) in C mode, so this shouldn't limit us too much.
10598 if (SubExprValue.isLValue())
10599 return false;
10600
10601 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", 10602, __extension__ __PRETTY_FUNCTION__
))
10602 "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", 10602, __extension__ __PRETTY_FUNCTION__
))
;
10603
10604 SmallVector<APValue, 4> ResultElements;
10605 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10606 llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10607 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10608 if (!Elt)
10609 return false;
10610 ResultElements.push_back(*Elt);
10611 }
10612 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10613}
10614
10615//===----------------------------------------------------------------------===//
10616// Array Evaluation
10617//===----------------------------------------------------------------------===//
10618
10619namespace {
10620 class ArrayExprEvaluator
10621 : public ExprEvaluatorBase<ArrayExprEvaluator> {
10622 const LValue &This;
10623 APValue &Result;
10624 public:
10625
10626 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10627 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10628
10629 bool Success(const APValue &V, const Expr *E) {
10630 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", 10630, __extension__ __PRETTY_FUNCTION__
))
;
10631 Result = V;
10632 return true;
10633 }
10634
10635 bool ZeroInitialization(const Expr *E) {
10636 const ConstantArrayType *CAT =
10637 Info.Ctx.getAsConstantArrayType(E->getType());
10638 if (!CAT) {
10639 if (E->getType()->isIncompleteArrayType()) {
10640 // We can be asked to zero-initialize a flexible array member; this
10641 // is represented as an ImplicitValueInitExpr of incomplete array
10642 // type. In this case, the array has zero elements.
10643 Result = APValue(APValue::UninitArray(), 0, 0);
10644 return true;
10645 }
10646 // FIXME: We could handle VLAs here.
10647 return Error(E);
10648 }
10649
10650 Result = APValue(APValue::UninitArray(), 0,
10651 CAT->getSize().getZExtValue());
10652 if (!Result.hasArrayFiller())
10653 return true;
10654
10655 // Zero-initialize all elements.
10656 LValue Subobject = This;
10657 Subobject.addArray(Info, E, CAT);
10658 ImplicitValueInitExpr VIE(CAT->getElementType());
10659 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10660 }
10661
10662 bool VisitCallExpr(const CallExpr *E) {
10663 return handleCallExpr(E, Result, &This);
10664 }
10665 bool VisitInitListExpr(const InitListExpr *E,
10666 QualType AllocType = QualType());
10667 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10668 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10669 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10670 const LValue &Subobject,
10671 APValue *Value, QualType Type);
10672 bool VisitStringLiteral(const StringLiteral *E,
10673 QualType AllocType = QualType()) {
10674 expandStringLiteral(Info, E, Result, AllocType);
10675 return true;
10676 }
10677 };
10678} // end anonymous namespace
10679
10680static bool EvaluateArray(const Expr *E, const LValue &This,
10681 APValue &Result, EvalInfo &Info) {
10682 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10682, __extension__ __PRETTY_FUNCTION__))
;
10683 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", 10684, __extension__ __PRETTY_FUNCTION__
))
10684 "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", 10684, __extension__ __PRETTY_FUNCTION__
))
;
10685 return ArrayExprEvaluator(Info, This, Result).Visit(E);
10686}
10687
10688static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10689 APValue &Result, const InitListExpr *ILE,
10690 QualType AllocType) {
10691 assert(!ILE->isValueDependent())(static_cast <bool> (!ILE->isValueDependent()) ? void
(0) : __assert_fail ("!ILE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10691, __extension__ __PRETTY_FUNCTION__))
;
1
Assuming the condition is true
2
'?' condition is true
10692 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", 10693, __extension__ __PRETTY_FUNCTION__
))
3
'?' condition is true
10693 "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", 10693, __extension__ __PRETTY_FUNCTION__
))
;
10694 return ArrayExprEvaluator(Info, This, Result)
4
Calling 'ArrayExprEvaluator::VisitInitListExpr'
10695 .VisitInitListExpr(ILE, AllocType);
10696}
10697
10698static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10699 APValue &Result,
10700 const CXXConstructExpr *CCE,
10701 QualType AllocType) {
10702 assert(!CCE->isValueDependent())(static_cast <bool> (!CCE->isValueDependent()) ? void
(0) : __assert_fail ("!CCE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 10702, __extension__ __PRETTY_FUNCTION__))
;
10703 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", 10704, __extension__ __PRETTY_FUNCTION__
))
10704 "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", 10704, __extension__ __PRETTY_FUNCTION__
))
;
10705 return ArrayExprEvaluator(Info, This, Result)
10706 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10707}
10708
10709// Return true iff the given array filler may depend on the element index.
10710static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10711 // For now, just allow non-class value-initialization and initialization
10712 // lists comprised of them.
10713 if (isa<ImplicitValueInitExpr>(FillerExpr))
10714 return false;
10715 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10716 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10717 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10718 return true;
10719 }
10720
10721 if (ILE->hasArrayFiller() &&
10722 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10723 return true;
10724
10725 return false;
10726 }
10727 return true;
10728}
10729
10730bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10731 QualType AllocType) {
10732 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10733 AllocType.isNull() ? E->getType() : AllocType);
5
'?' condition is false
10734 if (!CAT
5.1
'CAT' is non-null
)
6
Taking false branch
10735 return Error(E);
10736
10737 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10738 // an appropriately-typed string literal enclosed in braces.
10739 if (E->isStringLiteralInit()) {
7
Assuming the condition is false
10740 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10741 // FIXME: Support ObjCEncodeExpr here once we support it in
10742 // ArrayExprEvaluator generally.
10743 if (!SL)
10744 return Error(E);
10745 return VisitStringLiteral(SL, AllocType);
10746 }
10747 // Any other transparent list init will need proper handling of the
10748 // AllocType; we can't just recurse to the inner initializer.
10749 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", 10750, __extension__ __PRETTY_FUNCTION__
))
8
Taking false branch
9
Assuming the condition is true
10
'?' condition is true
10750 "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", 10750, __extension__ __PRETTY_FUNCTION__
))
;
10751
10752 bool Success = true;
10753
10754 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", 10755, __extension__ __PRETTY_FUNCTION__
))
11
'?' condition is true
10755 "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", 10755, __extension__ __PRETTY_FUNCTION__
))
;
10756 APValue Filler;
10757 if (Result.isArray() && Result.hasArrayFiller())
10758 Filler = Result.getArrayFiller();
10759
10760 unsigned NumEltsToInit = E->getNumInits();
10761 unsigned NumElts = CAT->getSize().getZExtValue();
10762 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
12
Assuming the condition is false
13
'?' condition is false
14
'FillerExpr' initialized to a null pointer value
10763
10764 // If the initializer might depend on the array index, run it for each
10765 // array element.
10766 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
15
Assuming 'NumEltsToInit' is equal to 'NumElts'
10767 NumEltsToInit = NumElts;
10768
10769 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)
16
Assuming 'DebugFlag' is false
17
Loop condition is false. Exiting loop
10770 << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: "
<< NumEltsToInit << ".\n"; } } while (false)
;
10771
10772 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10773
10774 // If the array was previously zero-initialized, preserve the
10775 // zero-initialized values.
10776 if (Filler.hasValue()) {
18
Taking false branch
10777 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10778 Result.getArrayInitializedElt(I) = Filler;
10779 if (Result.hasArrayFiller())
10780 Result.getArrayFiller() = Filler;
10781 }
10782
10783 LValue Subobject = This;
10784 Subobject.addArray(Info, E, CAT);
10785 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
19
Assuming 'Index' is not equal to 'NumEltsToInit'
10786 const Expr *Init =
20
Loop condition is true. Entering loop body
23
'Init' initialized to a null pointer value
10787 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
21
Assuming the condition is false
22
'?' condition is false
10788 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
24
Assuming the condition is false
10789 Info, Subobject, Init) ||
10790 !HandleLValueArrayAdjustment(Info, Init, Subobject,
25
Passing null pointer value via 2nd parameter 'E'
26
Calling 'HandleLValueArrayAdjustment'
10791 CAT->getElementType(), 1)) {
10792 if (!Info.noteFailure())
10793 return false;
10794 Success = false;
10795 }
10796 }
10797
10798 if (!Result.hasArrayFiller())
10799 return Success;
10800
10801 // If we get here, we have a trivial filler, which we can just evaluate
10802 // once and splat over the rest of the array elements.
10803 assert(FillerExpr && "no array filler for incomplete init list")(static_cast <bool> (FillerExpr && "no array filler for incomplete init list"
) ? void (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\""
, "clang/lib/AST/ExprConstant.cpp", 10803, __extension__ __PRETTY_FUNCTION__
))
;
10804 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10805 FillerExpr) && Success;
10806}
10807
10808bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10809 LValue CommonLV;
10810 if (E->getCommonExpr() &&
10811 !Evaluate(Info.CurrentCall->createTemporary(
10812 E->getCommonExpr(),
10813 getStorageType(Info.Ctx, E->getCommonExpr()),
10814 ScopeKind::FullExpression, CommonLV),
10815 Info, E->getCommonExpr()->getSourceExpr()))
10816 return false;
10817
10818 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10819
10820 uint64_t Elements = CAT->getSize().getZExtValue();
10821 Result = APValue(APValue::UninitArray(), Elements, Elements);
10822
10823 LValue Subobject = This;
10824 Subobject.addArray(Info, E, CAT);
10825
10826 bool Success = true;
10827 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10828 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10829 Info, Subobject, E->getSubExpr()) ||
10830 !HandleLValueArrayAdjustment(Info, E, Subobject,
10831 CAT->getElementType(), 1)) {
10832 if (!Info.noteFailure())
10833 return false;
10834 Success = false;
10835 }
10836 }
10837
10838 return Success;
10839}
10840
10841bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10842 return VisitCXXConstructExpr(E, This, &Result, E->getType());
10843}
10844
10845bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10846 const LValue &Subobject,
10847 APValue *Value,
10848 QualType Type) {
10849 bool HadZeroInit = Value->hasValue();
10850
10851 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10852 unsigned FinalSize = CAT->getSize().getZExtValue();
10853
10854 // Preserve the array filler if we had prior zero-initialization.
10855 APValue Filler =
10856 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10857 : APValue();
10858
10859 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10860 if (FinalSize == 0)
10861 return true;
10862
10863 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10864 Info, E->getExprLoc(), E->getConstructor(),
10865 E->requiresZeroInitialization());
10866 LValue ArrayElt = Subobject;
10867 ArrayElt.addArray(Info, E, CAT);
10868 // We do the whole initialization in two passes, first for just one element,
10869 // then for the whole array. It's possible we may find out we can't do const
10870 // init in the first pass, in which case we avoid allocating a potentially
10871 // large array. We don't do more passes because expanding array requires
10872 // copying the data, which is wasteful.
10873 for (const unsigned N : {1u, FinalSize}) {
10874 unsigned OldElts = Value->getArrayInitializedElts();
10875 if (OldElts == N)
10876 break;
10877
10878 // Expand the array to appropriate size.
10879 APValue NewValue(APValue::UninitArray(), N, FinalSize);
10880 for (unsigned I = 0; I < OldElts; ++I)
10881 NewValue.getArrayInitializedElt(I).swap(
10882 Value->getArrayInitializedElt(I));
10883 Value->swap(NewValue);
10884
10885 if (HadZeroInit)
10886 for (unsigned I = OldElts; I < N; ++I)
10887 Value->getArrayInitializedElt(I) = Filler;
10888
10889 if (HasTrivialConstructor && N == FinalSize) {
10890 // If we have a trivial constructor, only evaluate it once and copy
10891 // the result into all the array elements.
10892 APValue &FirstResult = Value->getArrayInitializedElt(0);
10893 for (unsigned I = OldElts; I < FinalSize; ++I)
10894 Value->getArrayInitializedElt(I) = FirstResult;
10895 } else {
10896 for (unsigned I = OldElts; I < N; ++I) {
10897 if (!VisitCXXConstructExpr(E, ArrayElt,
10898 &Value->getArrayInitializedElt(I),
10899 CAT->getElementType()) ||
10900 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10901 CAT->getElementType(), 1))
10902 return false;
10903 // When checking for const initilization any diagnostic is considered
10904 // an error.
10905 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10906 !Info.keepEvaluatingAfterFailure())
10907 return false;
10908 }
10909 }
10910 }
10911
10912 return true;
10913 }
10914
10915 if (!Type->isRecordType())
10916 return Error(E);
10917
10918 return RecordExprEvaluator(Info, Subobject, *Value)
10919 .VisitCXXConstructExpr(E, Type);
10920}
10921
10922//===----------------------------------------------------------------------===//
10923// Integer Evaluation
10924//
10925// As a GNU extension, we support casting pointers to sufficiently-wide integer
10926// types and back in constant folding. Integer values are thus represented
10927// either as an integer-valued APValue, or as an lvalue-valued APValue.
10928//===----------------------------------------------------------------------===//
10929
10930namespace {
10931class IntExprEvaluator
10932 : public ExprEvaluatorBase<IntExprEvaluator> {
10933 APValue &Result;
10934public:
10935 IntExprEvaluator(EvalInfo &info, APValue &result)
10936 : ExprEvaluatorBaseTy(info), Result(result) {}
10937
10938 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10939 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", 10940, __extension__ __PRETTY_FUNCTION__
))
10940 "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", 10940, __extension__ __PRETTY_FUNCTION__
))
;
10941 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", 10942, __extension__ __PRETTY_FUNCTION__
))
10942 "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", 10942, __extension__ __PRETTY_FUNCTION__
))
;
10943 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", 10944, __extension__ __PRETTY_FUNCTION__
))
10944 "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", 10944, __extension__ __PRETTY_FUNCTION__
))
;
10945 Result = APValue(SI);
10946 return true;
10947 }
10948 bool Success(const llvm::APSInt &SI, const Expr *E) {
10949 return Success(SI, E, Result);
10950 }
10951
10952 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10953 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", 10954, __extension__ __PRETTY_FUNCTION__
))
10954 "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", 10954, __extension__ __PRETTY_FUNCTION__
))
;
10955 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", 10956, __extension__ __PRETTY_FUNCTION__
))
10956 "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", 10956, __extension__ __PRETTY_FUNCTION__
))
;
10957 Result = APValue(APSInt(I));
10958 Result.getInt().setIsUnsigned(
10959 E->getType()->isUnsignedIntegerOrEnumerationType());
10960 return true;
10961 }
10962 bool Success(const llvm::APInt &I, const Expr *E) {
10963 return Success(I, E, Result);
10964 }
10965
10966 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10967 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", 10968, __extension__ __PRETTY_FUNCTION__
))
10968 "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", 10968, __extension__ __PRETTY_FUNCTION__
))
;
10969 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10970 return true;
10971 }
10972 bool Success(uint64_t Value, const Expr *E) {
10973 return Success(Value, E, Result);
10974 }
10975
10976 bool Success(CharUnits Size, const Expr *E) {
10977 return Success(Size.getQuantity(), E);
10978 }
10979
10980 bool Success(const APValue &V, const Expr *E) {
10981 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10982 Result = V;
10983 return true;
10984 }
10985 return Success(V.getInt(), E);
10986 }
10987
10988 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10989
10990 //===--------------------------------------------------------------------===//
10991 // Visitor Methods
10992 //===--------------------------------------------------------------------===//
10993
10994 bool VisitIntegerLiteral(const IntegerLiteral *E) {
10995 return Success(E->getValue(), E);
10996 }
10997 bool VisitCharacterLiteral(const CharacterLiteral *E) {
10998 return Success(E->getValue(), E);
10999 }
11000
11001 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11002 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11003 if (CheckReferencedDecl(E, E->getDecl()))
11004 return true;
11005
11006 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11007 }
11008 bool VisitMemberExpr(const MemberExpr *E) {
11009 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11010 VisitIgnoredBaseExpression(E->getBase());
11011 return true;
11012 }
11013
11014 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11015 }
11016
11017 bool VisitCallExpr(const CallExpr *E);
11018 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11019 bool VisitBinaryOperator(const BinaryOperator *E);
11020 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11021 bool VisitUnaryOperator(const UnaryOperator *E);
11022
11023 bool VisitCastExpr(const CastExpr* E);
11024 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11025
11026 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11027 return Success(E->getValue(), E);
11028 }
11029
11030 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11031 return Success(E->getValue(), E);
11032 }
11033
11034 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11035 if (Info.ArrayInitIndex == uint64_t(-1)) {
11036 // We were asked to evaluate this subexpression independent of the
11037 // enclosing ArrayInitLoopExpr. We can't do that.
11038 Info.FFDiag(E);
11039 return false;
11040 }
11041 return Success(Info.ArrayInitIndex, E);
11042 }
11043
11044 // Note, GNU defines __null as an integer, not a pointer.
11045 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11046 return ZeroInitialization(E);
11047 }
11048
11049 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11050 return Success(E->getValue(), E);
11051 }
11052
11053 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11054 return Success(E->getValue(), E);
11055 }
11056
11057 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11058 return Success(E->getValue(), E);
11059 }
11060
11061 bool VisitUnaryReal(const UnaryOperator *E);
11062 bool VisitUnaryImag(const UnaryOperator *E);
11063
11064 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11065 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11066 bool VisitSourceLocExpr(const SourceLocExpr *E);
11067 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11068 bool VisitRequiresExpr(const RequiresExpr *E);
11069 // FIXME: Missing: array subscript of vector, member of vector
11070};
11071
11072class FixedPointExprEvaluator
11073 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11074 APValue &Result;
11075
11076 public:
11077 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11078 : ExprEvaluatorBaseTy(info), Result(result) {}
11079
11080 bool Success(const llvm::APInt &I, const Expr *E) {
11081 return Success(
11082 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11083 }
11084
11085 bool Success(uint64_t Value, const Expr *E) {
11086 return Success(
11087 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11088 }
11089
11090 bool Success(const APValue &V, const Expr *E) {
11091 return Success(V.getFixedPoint(), E);
11092 }
11093
11094 bool Success(const APFixedPoint &V, const Expr *E) {
11095 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", 11095, __extension__ __PRETTY_FUNCTION__
))
;
11096 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", 11097, __extension__ __PRETTY_FUNCTION__
))
11097 "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", 11097, __extension__ __PRETTY_FUNCTION__
))
;
11098 Result = APValue(V);
11099 return true;
11100 }
11101
11102 //===--------------------------------------------------------------------===//
11103 // Visitor Methods
11104 //===--------------------------------------------------------------------===//
11105
11106 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11107 return Success(E->getValue(), E);
11108 }
11109
11110 bool VisitCastExpr(const CastExpr *E);
11111 bool VisitUnaryOperator(const UnaryOperator *E);
11112 bool VisitBinaryOperator(const BinaryOperator *E);
11113};
11114} // end anonymous namespace
11115
11116/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11117/// produce either the integer value or a pointer.
11118///
11119/// GCC has a heinous extension which folds casts between pointer types and
11120/// pointer-sized integral types. We support this by allowing the evaluation of
11121/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11122/// Some simple arithmetic on such values is supported (they are treated much
11123/// like char*).
11124static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11125 EvalInfo &Info) {
11126 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11126, __extension__ __PRETTY_FUNCTION__))
;
11127 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", 11127, __extension__ __PRETTY_FUNCTION__
))
;
11128 return IntExprEvaluator(Info, Result).Visit(E);
11129}
11130
11131static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11132 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11132, __extension__ __PRETTY_FUNCTION__))
;
11133 APValue Val;
11134 if (!EvaluateIntegerOrLValue(E, Val, Info))
11135 return false;
11136 if (!Val.isInt()) {
11137 // FIXME: It would be better to produce the diagnostic for casting
11138 // a pointer to an integer.
11139 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11140 return false;
11141 }
11142 Result = Val.getInt();
11143 return true;
11144}
11145
11146bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11147 APValue Evaluated = E->EvaluateInContext(
11148 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11149 return Success(Evaluated, E);
11150}
11151
11152static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11153 EvalInfo &Info) {
11154 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11154, __extension__ __PRETTY_FUNCTION__))
;
11155 if (E->getType()->isFixedPointType()) {
11156 APValue Val;
11157 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11158 return false;
11159 if (!Val.isFixedPoint())
11160 return false;
11161
11162 Result = Val.getFixedPoint();
11163 return true;
11164 }
11165 return false;
11166}
11167
11168static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11169 EvalInfo &Info) {
11170 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 11170, __extension__ __PRETTY_FUNCTION__))
;
11171 if (E->getType()->isIntegerType()) {
11172 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11173 APSInt Val;
11174 if (!EvaluateInteger(E, Val, Info))
11175 return false;
11176 Result = APFixedPoint(Val, FXSema);
11177 return true;
11178 } else if (E->getType()->isFixedPointType()) {
11179 return EvaluateFixedPoint(E, Result, Info);
11180 }
11181 return false;
11182}
11183
11184/// Check whether the given declaration can be directly converted to an integral
11185/// rvalue. If not, no diagnostic is produced; there are other things we can
11186/// try.
11187bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11188 // Enums are integer constant exprs.
11189 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11190 // Check for signedness/width mismatches between E type and ECD value.
11191 bool SameSign = (ECD->getInitVal().isSigned()
11192 == E->getType()->isSignedIntegerOrEnumerationType());
11193 bool SameWidth = (ECD->getInitVal().getBitWidth()
11194 == Info.Ctx.getIntWidth(E->getType()));
11195 if (SameSign && SameWidth)
11196 return Success(ECD->getInitVal(), E);
11197 else {
11198 // Get rid of mismatch (otherwise Success assertions will fail)
11199 // by computing a new value matching the type of E.
11200 llvm::APSInt Val = ECD->getInitVal();
11201 if (!SameSign)
11202 Val.setIsSigned(!ECD->getInitVal().isSigned());
11203 if (!SameWidth)
11204 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11205 return Success(Val, E);
11206 }
11207 }
11208 return false;
11209}
11210
11211/// Values returned by __builtin_classify_type, chosen to match the values
11212/// produced by GCC's builtin.
11213enum class GCCTypeClass {
11214 None = -1,
11215 Void = 0,
11216 Integer = 1,
11217 // GCC reserves 2 for character types, but instead classifies them as
11218 // integers.
11219 Enum = 3,
11220 Bool = 4,
11221 Pointer = 5,
11222 // GCC reserves 6 for references, but appears to never use it (because
11223 // expressions never have reference type, presumably).
11224 PointerToDataMember = 7,
11225 RealFloat = 8,
11226 Complex = 9,
11227 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11228 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11229 // GCC claims to reserve 11 for pointers to member functions, but *actually*
11230 // uses 12 for that purpose, same as for a class or struct. Maybe it
11231 // internally implements a pointer to member as a struct? Who knows.
11232 PointerToMemberFunction = 12, // Not a bug, see above.
11233 ClassOrStruct = 12,
11234 Union = 13,
11235 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11236 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11237 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11238 // literals.
11239};
11240
11241/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11242/// as GCC.
11243static GCCTypeClass
11244EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11245 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", 11245, __extension__ __PRETTY_FUNCTION__
))
;
11246
11247 QualType CanTy = T.getCanonicalType();
11248 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11249
11250 switch (CanTy->getTypeClass()) {
11251#define TYPE(ID, BASE)
11252#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11253#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11254#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11255#include "clang/AST/TypeNodes.inc"
11256 case Type::Auto:
11257 case Type::DeducedTemplateSpecialization:
11258 llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type"
, "clang/lib/AST/ExprConstant.cpp", 11258)
;
11259
11260 case Type::Builtin:
11261 switch (BT->getKind()) {
11262#define BUILTIN_TYPE(ID, SINGLETON_ID)
11263#define SIGNED_TYPE(ID, SINGLETON_ID) \
11264 case BuiltinType::ID: return GCCTypeClass::Integer;
11265#define FLOATING_TYPE(ID, SINGLETON_ID) \
11266 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11267#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11268 case BuiltinType::ID: break;
11269#include "clang/AST/BuiltinTypes.def"
11270 case BuiltinType::Void:
11271 return GCCTypeClass::Void;
11272
11273 case BuiltinType::Bool:
11274 return GCCTypeClass::Bool;
11275
11276 case BuiltinType::Char_U:
11277 case BuiltinType::UChar:
11278 case BuiltinType::WChar_U:
11279 case BuiltinType::Char8:
11280 case BuiltinType::Char16:
11281 case BuiltinType::Char32:
11282 case BuiltinType::UShort:
11283 case BuiltinType::UInt:
11284 case BuiltinType::ULong:
11285 case BuiltinType::ULongLong:
11286 case BuiltinType::UInt128:
11287 return GCCTypeClass::Integer;
11288
11289 case BuiltinType::UShortAccum:
11290 case BuiltinType::UAccum:
11291 case BuiltinType::ULongAccum:
11292 case BuiltinType::UShortFract:
11293 case BuiltinType::UFract:
11294 case BuiltinType::ULongFract:
11295 case BuiltinType::SatUShortAccum:
11296 case BuiltinType::SatUAccum:
11297 case BuiltinType::SatULongAccum:
11298 case BuiltinType::SatUShortFract:
11299 case BuiltinType::SatUFract:
11300 case BuiltinType::SatULongFract:
11301 return GCCTypeClass::None;
11302
11303 case BuiltinType::NullPtr:
11304
11305 case BuiltinType::ObjCId:
11306 case BuiltinType::ObjCClass:
11307 case BuiltinType::ObjCSel:
11308#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11309 case BuiltinType::Id:
11310#include "clang/Basic/OpenCLImageTypes.def"
11311#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11312 case BuiltinType::Id:
11313#include "clang/Basic/OpenCLExtensionTypes.def"
11314 case BuiltinType::OCLSampler:
11315 case BuiltinType::OCLEvent:
11316 case BuiltinType::OCLClkEvent:
11317 case BuiltinType::OCLQueue:
11318 case BuiltinType::OCLReserveID:
11319#define SVE_TYPE(Name, Id, SingletonId) \
11320 case BuiltinType::Id:
11321#include "clang/Basic/AArch64SVEACLETypes.def"
11322#define PPC_VECTOR_TYPE(Name, Id, Size) \
11323 case BuiltinType::Id:
11324#include "clang/Basic/PPCTypes.def"
11325#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11326#include "clang/Basic/RISCVVTypes.def"
11327 return GCCTypeClass::None;
11328
11329 case BuiltinType::Dependent:
11330 llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type"
, "clang/lib/AST/ExprConstant.cpp", 11330)
;
11331 };
11332 llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type"
, "clang/lib/AST/ExprConstant.cpp", 11332)
;
11333
11334 case Type::Enum:
11335 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11336
11337 case Type::Pointer:
11338 case Type::ConstantArray:
11339 case Type::VariableArray:
11340 case Type::IncompleteArray:
11341 case Type::FunctionNoProto:
11342 case Type::FunctionProto:
11343 return GCCTypeClass::Pointer;
11344
11345 case Type::MemberPointer:
11346 return CanTy->isMemberDataPointerType()
11347 ? GCCTypeClass::PointerToDataMember
11348 : GCCTypeClass::PointerToMemberFunction;
11349
11350 case Type::Complex:
11351 return GCCTypeClass::Complex;
11352
11353 case Type::Record:
11354 return CanTy->isUnionType() ? GCCTypeClass::Union
11355 : GCCTypeClass::ClassOrStruct;
11356
11357 case Type::Atomic:
11358 // GCC classifies _Atomic T the same as T.
11359 return EvaluateBuiltinClassifyType(
11360 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11361
11362 case Type::BlockPointer:
11363 case Type::Vector:
11364 case Type::ExtVector:
11365 case Type::ConstantMatrix:
11366 case Type::ObjCObject:
11367 case Type::ObjCInterface:
11368 case Type::ObjCObjectPointer:
11369 case Type::Pipe:
11370 case Type::BitInt:
11371 // GCC classifies vectors as None. We follow its lead and classify all
11372 // other types that don't fit into the regular classification the same way.
11373 return GCCTypeClass::None;
11374
11375 case Type::LValueReference:
11376 case Type::RValueReference:
11377 llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression"
, "clang/lib/AST/ExprConstant.cpp", 11377)
;
11378 }
11379
11380 llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "clang/lib/AST/ExprConstant.cpp"
, 11380)
;
11381}
11382
11383/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11384/// as GCC.
11385static GCCTypeClass
11386EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11387 // If no argument was supplied, default to None. This isn't
11388 // ideal, however it is what gcc does.
11389 if (E->getNumArgs() == 0)
11390 return GCCTypeClass::None;
11391
11392 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11393 // being an ICE, but still folds it to a constant using the type of the first
11394 // argument.
11395 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11396}
11397
11398/// EvaluateBuiltinConstantPForLValue - Determine the result of
11399/// __builtin_constant_p when applied to the given pointer.
11400///
11401/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11402/// or it points to the first character of a string literal.
11403static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11404 APValue::LValueBase Base = LV.getLValueBase();
11405 if (Base.isNull()) {
11406 // A null base is acceptable.
11407 return true;
11408 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11409 if (!isa<StringLiteral>(E))
11410 return false;
11411 return LV.getLValueOffset().isZero();
11412 } else if (Base.is<TypeInfoLValue>()) {
11413 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11414 // evaluate to true.
11415 return true;
11416 } else {
11417 // Any other base is not constant enough for GCC.
11418 return false;
11419 }
11420}
11421
11422/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11423/// GCC as we can manage.
11424static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11425 // This evaluation is not permitted to have side-effects, so evaluate it in
11426 // a speculative evaluation context.
11427 SpeculativeEvaluationRAII SpeculativeEval(Info);
11428
11429 // Constant-folding is always enabled for the operand of __builtin_constant_p
11430 // (even when the enclosing evaluation context otherwise requires a strict
11431 // language-specific constant expression).
11432 FoldConstant Fold(Info, true);
11433
11434 QualType ArgType = Arg->getType();
11435
11436 // __builtin_constant_p always has one operand. The rules which gcc follows
11437 // are not precisely documented, but are as follows:
11438 //
11439 // - If the operand is of integral, floating, complex or enumeration type,
11440 // and can be folded to a known value of that type, it returns 1.
11441 // - If the operand can be folded to a pointer to the first character
11442 // of a string literal (or such a pointer cast to an integral type)
11443 // or to a null pointer or an integer cast to a pointer, it returns 1.
11444 //
11445 // Otherwise, it returns 0.
11446 //
11447 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11448 // its support for this did not work prior to GCC 9 and is not yet well
11449 // understood.
11450 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11451 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11452 ArgType->isNullPtrType()) {
11453 APValue V;
11454 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11455 Fold.keepDiagnostics();
11456 return false;
11457 }
11458
11459 // For a pointer (possibly cast to integer), there are special rules.
11460 if (V.getKind() == APValue::LValue)
11461 return EvaluateBuiltinConstantPForLValue(V);
11462
11463 // Otherwise, any constant value is good enough.
11464 return V.hasValue();
11465 }
11466
11467 // Anything else isn't considered to be sufficiently constant.
11468 return false;
11469}
11470
11471/// Retrieves the "underlying object type" of the given expression,
11472/// as used by __builtin_object_size.
11473static QualType getObjectType(APValue::LValueBase B) {
11474 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11475 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11476 return VD->getType();
11477 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11478 if (isa<CompoundLiteralExpr>(E))
11479 return E->getType();
11480 } else if (B.is<TypeInfoLValue>()) {
11481 return B.getTypeInfoType();
11482 } else if (B.is<DynamicAllocLValue>()) {
11483 return B.getDynamicAllocType();
11484 }
11485
11486 return QualType();
11487}
11488
11489/// A more selective version of E->IgnoreParenCasts for
11490/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11491/// to change the type of E.
11492/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11493///
11494/// Always returns an RValue with a pointer representation.
11495static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11496 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", 11496, __extension__ __PRETTY_FUNCTION__
))
;
11497
11498 auto *NoParens = E->IgnoreParens();
11499 auto *Cast = dyn_cast<CastExpr>(NoParens);
11500 if (Cast == nullptr)
11501 return NoParens;
11502
11503 // We only conservatively allow a few kinds of casts, because this code is
11504 // inherently a simple solution that seeks to support the common case.
11505 auto CastKind = Cast->getCastKind();
11506 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11507 CastKind != CK_AddressSpaceConversion)
11508 return NoParens;
11509
11510 auto *SubExpr = Cast->getSubExpr();
11511 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11512 return NoParens;
11513 return ignorePointerCastsAndParens(SubExpr);
11514}
11515
11516/// Checks to see if the given LValue's Designator is at the end of the LValue's
11517/// record layout. e.g.
11518/// struct { struct { int a, b; } fst, snd; } obj;
11519/// obj.fst // no
11520/// obj.snd // yes
11521/// obj.fst.a // no
11522/// obj.fst.b // no
11523/// obj.snd.a // no
11524/// obj.snd.b // yes
11525///
11526/// Please note: this function is specialized for how __builtin_object_size
11527/// views "objects".
11528///
11529/// If this encounters an invalid RecordDecl or otherwise cannot determine the
11530/// correct result, it will always return true.
11531static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11532 assert(!LVal.Designator.Invalid)(static_cast <bool> (!LVal.Designator.Invalid) ? void (
0) : __assert_fail ("!LVal.Designator.Invalid", "clang/lib/AST/ExprConstant.cpp"
, 11532, __extension__ __PRETTY_FUNCTION__))
;
11533
11534 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11535 const RecordDecl *Parent = FD->getParent();
11536 Invalid = Parent->isInvalidDecl();
11537 if (Invalid || Parent->isUnion())
11538 return true;
11539 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11540 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11541 };
11542
11543 auto &Base = LVal.getLValueBase();
11544 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11545 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11546 bool Invalid;
11547 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11548 return Invalid;
11549 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11550 for (auto *FD : IFD->chain()) {
11551 bool Invalid;
11552 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11553 return Invalid;
11554 }
11555 }
11556 }
11557
11558 unsigned I = 0;
11559 QualType BaseType = getType(Base);
11560 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11561 // If we don't know the array bound, conservatively assume we're looking at
11562 // the final array element.
11563 ++I;
11564 if (BaseType->isIncompleteArrayType())
11565 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11566 else
11567 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11568 }
11569
11570 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11571 const auto &Entry = LVal.Designator.Entries[I];
11572 if (BaseType->isArrayType()) {
11573 // Because __builtin_object_size treats arrays as objects, we can ignore
11574 // the index iff this is the last array in the Designator.
11575 if (I + 1 == E)
11576 return true;
11577 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11578 uint64_t Index = Entry.getAsArrayIndex();
11579 if (Index + 1 != CAT->getSize())
11580 return false;
11581 BaseType = CAT->getElementType();
11582 } else if (BaseType->isAnyComplexType()) {
11583 const auto *CT = BaseType->castAs<ComplexType>();
11584 uint64_t Index = Entry.getAsArrayIndex();
11585 if (Index != 1)
11586 return false;
11587 BaseType = CT->getElementType();
11588 } else if (auto *FD = getAsField(Entry)) {
11589 bool Invalid;
11590 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11591 return Invalid;
11592 BaseType = FD->getType();
11593 } else {
11594 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", 11594, __extension__ __PRETTY_FUNCTION__
))
;
11595 return false;
11596 }
11597 }
11598 return true;
11599}
11600
11601/// Tests to see if the LValue has a user-specified designator (that isn't
11602/// necessarily valid). Note that this always returns 'true' if the LValue has
11603/// an unsized array as its first designator entry, because there's currently no
11604/// way to tell if the user typed *foo or foo[0].
11605static bool refersToCompleteObject(const LValue &LVal) {
11606 if (LVal.Designator.Invalid)
11607 return false;
11608
11609 if (!LVal.Designator.Entries.empty())
11610 return LVal.Designator.isMostDerivedAnUnsizedArray();
11611
11612 if (!LVal.InvalidBase)
11613 return true;
11614
11615 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11616 // the LValueBase.
11617 const auto *E = LVal.Base.dyn_cast<const Expr *>();
11618 return !E || !isa<MemberExpr>(E);
11619}
11620
11621/// Attempts to detect a user writing into a piece of memory that's impossible
11622/// to figure out the size of by just using types.
11623static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11624 const SubobjectDesignator &Designator = LVal.Designator;
11625 // Notes:
11626 // - Users can only write off of the end when we have an invalid base. Invalid
11627 // bases imply we don't know where the memory came from.
11628 // - We used to be a bit more aggressive here; we'd only be conservative if
11629 // the array at the end was flexible, or if it had 0 or 1 elements. This
11630 // broke some common standard library extensions (PR30346), but was
11631 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11632 // with some sort of list. OTOH, it seems that GCC is always
11633 // conservative with the last element in structs (if it's an array), so our
11634 // current behavior is more compatible than an explicit list approach would
11635 // be.
11636 auto isFlexibleArrayMember = [&] {
11637 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11638 FAMKind StrictFlexArraysLevel =
11639 Ctx.getLangOpts().getStrictFlexArraysLevel();
11640
11641 if (Designator.isMostDerivedAnUnsizedArray())
11642 return true;
11643
11644 if (StrictFlexArraysLevel == FAMKind::Default)
11645 return true;
11646
11647 if (Designator.getMostDerivedArraySize() == 0 &&
11648 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11649 return true;
11650
11651 if (Designator.getMostDerivedArraySize() == 1 &&
11652 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11653 return true;
11654
11655 return false;
11656 };
11657
11658 return LVal.InvalidBase &&
11659 Designator.Entries.size() == Designator.MostDerivedPathLength &&
11660 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11661 isDesignatorAtObjectEnd(Ctx, LVal);
11662}
11663
11664/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11665/// Fails if the conversion would cause loss of precision.
11666static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11667 CharUnits &Result) {
11668 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11669 if (Int.ugt(CharUnitsMax))
11670 return false;
11671 Result = CharUnits::fromQuantity(Int.getZExtValue());
11672 return true;
11673}
11674
11675/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11676/// determine how many bytes exist from the beginning of the object to either
11677/// the end of the current subobject, or the end of the object itself, depending
11678/// on what the LValue looks like + the value of Type.
11679///
11680/// If this returns false, the value of Result is undefined.
11681static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11682 unsigned Type, const LValue &LVal,
11683 CharUnits &EndOffset) {
11684 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11685
11686 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11687 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11688 return false;
11689 return HandleSizeof(Info, ExprLoc, Ty, Result);
11690 };
11691
11692 // We want to evaluate the size of the entire object. This is a valid fallback
11693 // for when Type=1 and the designator is invalid, because we're asked for an
11694 // upper-bound.
11695 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11696 // Type=3 wants a lower bound, so we can't fall back to this.
11697 if (Type == 3 && !DetermineForCompleteObject)
11698 return false;
11699
11700 llvm::APInt APEndOffset;
11701 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11702 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11703 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11704
11705 if (LVal.InvalidBase)
11706 return false;
11707
11708 QualType BaseTy = getObjectType(LVal.getLValueBase());
11709 return CheckedHandleSizeof(BaseTy, EndOffset);
11710 }
11711
11712 // We want to evaluate the size of a subobject.
11713 const SubobjectDesignator &Designator = LVal.Designator;
11714
11715 // The following is a moderately common idiom in C:
11716 //
11717 // struct Foo { int a; char c[1]; };
11718 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11719 // strcpy(&F->c[0], Bar);
11720 //
11721 // In order to not break too much legacy code, we need to support it.
11722 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11723 // If we can resolve this to an alloc_size call, we can hand that back,
11724 // because we know for certain how many bytes there are to write to.
11725 llvm::APInt APEndOffset;
11726 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11727 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11728 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11729
11730 // If we cannot determine the size of the initial allocation, then we can't
11731 // given an accurate upper-bound. However, we are still able to give
11732 // conservative lower-bounds for Type=3.
11733 if (Type == 1)
11734 return false;
11735 }
11736
11737 CharUnits BytesPerElem;
11738 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11739 return false;
11740
11741 // According to the GCC documentation, we want the size of the subobject
11742 // denoted by the pointer. But that's not quite right -- what we actually
11743 // want is the size of the immediately-enclosing array, if there is one.
11744 int64_t ElemsRemaining;
11745 if (Designator.MostDerivedIsArrayElement &&
11746 Designator.Entries.size() == Designator.MostDerivedPathLength) {
11747 uint64_t ArraySize = Designator.getMostDerivedArraySize();
11748 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11749 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11750 } else {
11751 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11752 }
11753
11754 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11755 return true;
11756}
11757
11758/// Tries to evaluate the __builtin_object_size for @p E. If successful,
11759/// returns true and stores the result in @p Size.
11760///
11761/// If @p WasError is non-null, this will report whether the failure to evaluate
11762/// is to be treated as an Error in IntExprEvaluator.
11763static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11764 EvalInfo &Info, uint64_t &Size) {
11765 // Determine the denoted object.
11766 LValue LVal;
11767 {
11768 // The operand of __builtin_object_size is never evaluated for side-effects.
11769 // If there are any, but we can determine the pointed-to object anyway, then
11770 // ignore the side-effects.
11771 SpeculativeEvaluationRAII SpeculativeEval(Info);
11772 IgnoreSideEffectsRAII Fold(Info);
11773
11774 if (E->isGLValue()) {
11775 // It's possible for us to be given GLValues if we're called via
11776 // Expr::tryEvaluateObjectSize.
11777 APValue RVal;
11778 if (!EvaluateAsRValue(Info, E, RVal))
11779 return false;
11780 LVal.setFrom(Info.Ctx, RVal);
11781 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11782 /*InvalidBaseOK=*/true))
11783 return false;
11784 }
11785
11786 // If we point to before the start of the object, there are no accessible
11787 // bytes.
11788 if (LVal.getLValueOffset().isNegative()) {
11789 Size = 0;
11790 return true;
11791 }
11792
11793 CharUnits EndOffset;
11794 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11795 return false;
11796
11797 // If we've fallen outside of the end offset, just pretend there's nothing to
11798 // write to/read from.
11799 if (EndOffset <= LVal.getLValueOffset())
11800 Size = 0;
11801 else
11802 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11803 return true;
11804}
11805
11806bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11807 if (!IsConstantEvaluatedBuiltinCall(E))
11808 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11809 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11810}
11811
11812static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11813 APValue &Val, APSInt &Alignment) {
11814 QualType SrcTy = E->getArg(0)->getType();
11815 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11816 return false;
11817 // Even though we are evaluating integer expressions we could get a pointer
11818 // argument for the __builtin_is_aligned() case.
11819 if (SrcTy->isPointerType()) {
11820 LValue Ptr;
11821 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11822 return false;
11823 Ptr.moveInto(Val);
11824 } else if (!SrcTy->isIntegralOrEnumerationType()) {
11825 Info.FFDiag(E->getArg(0));
11826 return false;
11827 } else {
11828 APSInt SrcInt;
11829 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11830 return false;
11831 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", 11832, __extension__ __PRETTY_FUNCTION__
))
11832 "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", 11832, __extension__ __PRETTY_FUNCTION__
))
;
11833 Val = APValue(SrcInt);
11834 }
11835 assert(Val.hasValue())(static_cast <bool> (Val.hasValue()) ? void (0) : __assert_fail
("Val.hasValue()", "clang/lib/AST/ExprConstant.cpp", 11835, __extension__
__PRETTY_FUNCTION__))
;
11836 return true;
11837}
11838
11839bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11840 unsigned BuiltinOp) {
11841 switch (BuiltinOp) {
11842 default:
11843 return false;
11844
11845 case Builtin::BI__builtin_dynamic_object_size:
11846 case Builtin::BI__builtin_object_size: {
11847 // The type was checked when we built the expression.
11848 unsigned Type =
11849 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11850 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", 11850, __extension__ __PRETTY_FUNCTION__
))
;
11851
11852 uint64_t Size;
11853 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11854 return Success(Size, E);
11855
11856 if (E->getArg(0)->HasSideEffects(Info.Ctx))
11857 return Success((Type & 2) ? 0 : -1, E);
11858
11859 // Expression had no side effects, but we couldn't statically determine the
11860 // size of the referenced object.
11861 switch (Info.EvalMode) {
11862 case EvalInfo::EM_ConstantExpression:
11863 case EvalInfo::EM_ConstantFold:
11864 case EvalInfo::EM_IgnoreSideEffects:
11865 // Leave it to IR generation.
11866 return Error(E);
11867 case EvalInfo::EM_ConstantExpressionUnevaluated:
11868 // Reduce it to a constant now.
11869 return Success((Type & 2) ? 0 : -1, E);
11870 }
11871
11872 llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "clang/lib/AST/ExprConstant.cpp"
, 11872)
;
11873 }
11874
11875 case Builtin::BI__builtin_os_log_format_buffer_size: {
11876 analyze_os_log::OSLogBufferLayout Layout;
11877 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11878 return Success(Layout.size().getQuantity(), E);
11879 }
11880
11881 case Builtin::BI__builtin_is_aligned: {
11882 APValue Src;
11883 APSInt Alignment;
11884 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11885 return false;
11886 if (Src.isLValue()) {
11887 // If we evaluated a pointer, check the minimum known alignment.
11888 LValue Ptr;
11889 Ptr.setFrom(Info.Ctx, Src);
11890 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11891 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11892 // We can return true if the known alignment at the computed offset is
11893 // greater than the requested alignment.
11894 assert(PtrAlign.isPowerOfTwo())(static_cast <bool> (PtrAlign.isPowerOfTwo()) ? void (0
) : __assert_fail ("PtrAlign.isPowerOfTwo()", "clang/lib/AST/ExprConstant.cpp"
, 11894, __extension__ __PRETTY_FUNCTION__))
;
11895 assert(Alignment.isPowerOf2())(static_cast <bool> (Alignment.isPowerOf2()) ? void (0)
: __assert_fail ("Alignment.isPowerOf2()", "clang/lib/AST/ExprConstant.cpp"
, 11895, __extension__ __PRETTY_FUNCTION__))
;
11896 if (PtrAlign.getQuantity() >= Alignment)
11897 return Success(1, E);
11898 // If the alignment is not known to be sufficient, some cases could still
11899 // be aligned at run time. However, if the requested alignment is less or
11900 // equal to the base alignment and the offset is not aligned, we know that
11901 // the run-time value can never be aligned.
11902 if (BaseAlignment.getQuantity() >= Alignment &&
11903 PtrAlign.getQuantity() < Alignment)
11904 return Success(0, E);
11905 // Otherwise we can't infer whether the value is sufficiently aligned.
11906 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11907 // in cases where we can't fully evaluate the pointer.
11908 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11909 << Alignment;
11910 return false;
11911 }
11912 assert(Src.isInt())(static_cast <bool> (Src.isInt()) ? void (0) : __assert_fail
("Src.isInt()", "clang/lib/AST/ExprConstant.cpp", 11912, __extension__
__PRETTY_FUNCTION__))
;
11913 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11914 }
11915 case Builtin::BI__builtin_align_up: {
11916 APValue Src;
11917 APSInt Alignment;
11918 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11919 return false;
11920 if (!Src.isInt())
11921 return Error(E);
11922 APSInt AlignedVal =
11923 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11924 Src.getInt().isUnsigned());
11925 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", 11925, __extension__ __PRETTY_FUNCTION__
))
;
11926 return Success(AlignedVal, E);
11927 }
11928 case Builtin::BI__builtin_align_down: {
11929 APValue Src;
11930 APSInt Alignment;
11931 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11932 return false;
11933 if (!Src.isInt())
11934 return Error(E);
11935 APSInt AlignedVal =
11936 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11937 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", 11937, __extension__ __PRETTY_FUNCTION__
))
;
11938 return Success(AlignedVal, E);
11939 }
11940
11941 case Builtin::BI__builtin_bitreverse8:
11942 case Builtin::BI__builtin_bitreverse16:
11943 case Builtin::BI__builtin_bitreverse32:
11944 case Builtin::BI__builtin_bitreverse64: {
11945 APSInt Val;
11946 if (!EvaluateInteger(E->getArg(0), Val, Info))
11947 return false;
11948
11949 return Success(Val.reverseBits(), E);
11950 }
11951
11952 case Builtin::BI__builtin_bswap16:
11953 case Builtin::BI__builtin_bswap32:
11954 case Builtin::BI__builtin_bswap64: {
11955 APSInt Val;
11956 if (!EvaluateInteger(E->getArg(0), Val, Info))
11957 return false;
11958
11959 return Success(Val.byteSwap(), E);
11960 }
11961
11962 case Builtin::BI__builtin_classify_type:
11963 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11964
11965 case Builtin::BI__builtin_clrsb:
11966 case Builtin::BI__builtin_clrsbl:
11967 case Builtin::BI__builtin_clrsbll: {
11968 APSInt Val;
11969 if (!EvaluateInteger(E->getArg(0), Val, Info))
11970 return false;
11971
11972 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11973 }
11974
11975 case Builtin::BI__builtin_clz:
11976 case Builtin::BI__builtin_clzl:
11977 case Builtin::BI__builtin_clzll:
11978 case Builtin::BI__builtin_clzs: {
11979 APSInt Val;
11980 if (!EvaluateInteger(E->getArg(0), Val, Info))
11981 return false;
11982 if (!Val)
11983 return Error(E);
11984
11985 return Success(Val.countLeadingZeros(), E);
11986 }
11987
11988 case Builtin::BI__builtin_constant_p: {
11989 const Expr *Arg = E->getArg(0);
11990 if (EvaluateBuiltinConstantP(Info, Arg))
11991 return Success(true, E);
11992 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11993 // Outside a constant context, eagerly evaluate to false in the presence
11994 // of side-effects in order to avoid -Wunsequenced false-positives in
11995 // a branch on __builtin_constant_p(expr).
11996 return Success(false, E);
11997 }
11998 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11999 return false;
12000 }
12001
12002 case Builtin::BI__builtin_is_constant_evaluated: {
12003 const auto *Callee = Info.CurrentCall->getCallee();
12004 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12005 (Info.CallStackDepth == 1 ||
12006 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12007 Callee->getIdentifier() &&
12008 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12009 // FIXME: Find a better way to avoid duplicated diagnostics.
12010 if (Info.EvalStatus.Diag)
12011 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12012 : Info.CurrentCall->CallLoc,
12013 diag::warn_is_constant_evaluated_always_true_constexpr)
12014 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12015 : "std::is_constant_evaluated");
12016 }
12017
12018 return Success(Info.InConstantContext, E);
12019 }
12020
12021 case Builtin::BI__builtin_ctz:
12022 case Builtin::BI__builtin_ctzl:
12023 case Builtin::BI__builtin_ctzll:
12024 case Builtin::BI__builtin_ctzs: {
12025 APSInt Val;
12026 if (!EvaluateInteger(E->getArg(0), Val, Info))
12027 return false;
12028 if (!Val)
12029 return Error(E);
12030
12031 return Success(Val.countTrailingZeros(), E);
12032 }
12033
12034 case Builtin::BI__builtin_eh_return_data_regno: {
12035 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12036 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12037 return Success(Operand, E);
12038 }
12039
12040 case Builtin::BI__builtin_expect:
12041 case Builtin::BI__builtin_expect_with_probability:
12042 return Visit(E->getArg(0));
12043
12044 case Builtin::BI__builtin_ffs:
12045 case Builtin::BI__builtin_ffsl:
12046 case Builtin::BI__builtin_ffsll: {
12047 APSInt Val;
12048 if (!EvaluateInteger(E->getArg(0), Val, Info))
12049 return false;
12050
12051 unsigned N = Val.countTrailingZeros();
12052 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12053 }
12054
12055 case Builtin::BI__builtin_fpclassify: {
12056 APFloat Val(0.0);
12057 if (!EvaluateFloat(E->getArg(5), Val, Info))
12058 return false;
12059 unsigned Arg;
12060 switch (Val.getCategory()) {
12061 case APFloat::fcNaN: Arg = 0; break;
12062 case APFloat::fcInfinity: Arg = 1; break;
12063 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12064 case APFloat::fcZero: Arg = 4; break;
12065 }
12066 return Visit(E->getArg(Arg));
12067 }
12068
12069 case Builtin::BI__builtin_isinf_sign: {
12070 APFloat Val(0.0);
12071 return EvaluateFloat(E->getArg(0), Val, Info) &&
12072 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12073 }
12074
12075 case Builtin::BI__builtin_isinf: {
12076 APFloat Val(0.0);
12077 return EvaluateFloat(E->getArg(0), Val, Info) &&
12078 Success(Val.isInfinity() ? 1 : 0, E);
12079 }
12080
12081 case Builtin::BI__builtin_isfinite: {
12082 APFloat Val(0.0);
12083 return EvaluateFloat(E->getArg(0), Val, Info) &&
12084 Success(Val.isFinite() ? 1 : 0, E);
12085 }
12086
12087 case Builtin::BI__builtin_isnan: {
12088 APFloat Val(0.0);
12089 return EvaluateFloat(E->getArg(0), Val, Info) &&
12090 Success(Val.isNaN() ? 1 : 0, E);
12091 }
12092
12093 case Builtin::BI__builtin_isnormal: {
12094 APFloat Val(0.0);
12095 return EvaluateFloat(E->getArg(0), Val, Info) &&
12096 Success(Val.isNormal() ? 1 : 0, E);
12097 }
12098
12099 case Builtin::BI__builtin_parity:
12100 case Builtin::BI__builtin_parityl:
12101 case Builtin::BI__builtin_parityll: {
12102 APSInt Val;
12103 if (!EvaluateInteger(E->getArg(0), Val, Info))
12104 return false;
12105
12106 return Success(Val.countPopulation() % 2, E);
12107 }
12108
12109 case Builtin::BI__builtin_popcount:
12110 case Builtin::BI__builtin_popcountl:
12111 case Builtin::BI__builtin_popcountll: {
12112 APSInt Val;
12113 if (!EvaluateInteger(E->getArg(0), Val, Info))
12114 return false;
12115
12116 return Success(Val.countPopulation(), E);
12117 }
12118
12119 case Builtin::BI__builtin_rotateleft8:
12120 case Builtin::BI__builtin_rotateleft16:
12121 case Builtin::BI__builtin_rotateleft32:
12122 case Builtin::BI__builtin_rotateleft64:
12123 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12124 case Builtin::BI_rotl16:
12125 case Builtin::BI_rotl:
12126 case Builtin::BI_lrotl:
12127 case Builtin::BI_rotl64: {
12128 APSInt Val, Amt;
12129 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12130 !EvaluateInteger(E->getArg(1), Amt, Info))
12131 return false;
12132
12133 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12134 }
12135
12136 case Builtin::BI__builtin_rotateright8:
12137 case Builtin::BI__builtin_rotateright16:
12138 case Builtin::BI__builtin_rotateright32:
12139 case Builtin::BI__builtin_rotateright64:
12140 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12141 case Builtin::BI_rotr16:
12142 case Builtin::BI_rotr:
12143 case Builtin::BI_lrotr:
12144 case Builtin::BI_rotr64: {
12145 APSInt Val, Amt;
12146 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12147 !EvaluateInteger(E->getArg(1), Amt, Info))
12148 return false;
12149
12150 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12151 }
12152
12153 case Builtin::BIstrlen:
12154 case Builtin::BIwcslen:
12155 // A call to strlen is not a constant expression.
12156 if (Info.getLangOpts().CPlusPlus11)
12157 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12158 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12159 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12160 else
12161 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12162 [[fallthrough]];
12163 case Builtin::BI__builtin_strlen:
12164 case Builtin::BI__builtin_wcslen: {
12165 // As an extension, we support __builtin_strlen() as a constant expression,
12166 // and support folding strlen() to a constant.
12167 uint64_t StrLen;
12168 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12169 return Success(StrLen, E);
12170 return false;
12171 }
12172
12173 case Builtin::BIstrcmp:
12174 case Builtin::BIwcscmp:
12175 case Builtin::BIstrncmp:
12176 case Builtin::BIwcsncmp:
12177 case Builtin::BImemcmp:
12178 case Builtin::BIbcmp:
12179 case Builtin::BIwmemcmp:
12180 // A call to strlen is not a constant expression.
12181 if (Info.getLangOpts().CPlusPlus11)
12182 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12183 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12184 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12185 else
12186 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12187 [[fallthrough]];
12188 case Builtin::BI__builtin_strcmp:
12189 case Builtin::BI__builtin_wcscmp:
12190 case Builtin::BI__builtin_strncmp:
12191 case Builtin::BI__builtin_wcsncmp:
12192 case Builtin::BI__builtin_memcmp:
12193 case Builtin::BI__builtin_bcmp:
12194 case Builtin::BI__builtin_wmemcmp: {
12195 LValue String1, String2;
12196 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12197 !EvaluatePointer(E->getArg(1), String2, Info))
12198 return false;
12199
12200 uint64_t MaxLength = uint64_t(-1);
12201 if (BuiltinOp != Builtin::BIstrcmp &&
12202 BuiltinOp != Builtin::BIwcscmp &&
12203 BuiltinOp != Builtin::BI__builtin_strcmp &&
12204 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12205 APSInt N;
12206 if (!EvaluateInteger(E->getArg(2), N, Info))
12207 return false;
12208 MaxLength = N.getExtValue();
12209 }
12210
12211 // Empty substrings compare equal by definition.
12212 if (MaxLength == 0u)
12213 return Success(0, E);
12214
12215 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12216 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12217 String1.Designator.Invalid || String2.Designator.Invalid)
12218 return false;
12219
12220 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12221 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12222
12223 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12224 BuiltinOp == Builtin::BIbcmp ||
12225 BuiltinOp == Builtin::BI__builtin_memcmp ||
12226 BuiltinOp == Builtin::BI__builtin_bcmp;
12227
12228 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", 12231, __extension__ __PRETTY_FUNCTION__
))
12229 (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", 12231, __extension__ __PRETTY_FUNCTION__
))
12230 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", 12231, __extension__ __PRETTY_FUNCTION__
))
12231 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", 12231, __extension__ __PRETTY_FUNCTION__
))
;
12232
12233 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12234 // 'char8_t', but no other types.
12235 if (IsRawByte &&
12236 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12237 // FIXME: Consider using our bit_cast implementation to support this.
12238 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12239 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12240 << CharTy1 << CharTy2;
12241 return false;
12242 }
12243
12244 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12245 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12246 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12247 Char1.isInt() && Char2.isInt();
12248 };
12249 const auto &AdvanceElems = [&] {
12250 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12251 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12252 };
12253
12254 bool StopAtNull =
12255 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12256 BuiltinOp != Builtin::BIwmemcmp &&
12257 BuiltinOp != Builtin::BI__builtin_memcmp &&
12258 BuiltinOp != Builtin::BI__builtin_bcmp &&
12259 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12260 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12261 BuiltinOp == Builtin::BIwcsncmp ||
12262 BuiltinOp == Builtin::BIwmemcmp ||
12263 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12264 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12265 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12266
12267 for (; MaxLength; --MaxLength) {
12268 APValue Char1, Char2;
12269 if (!ReadCurElems(Char1, Char2))
12270 return false;
12271 if (Char1.getInt().ne(Char2.getInt())) {
12272 if (IsWide) // wmemcmp compares with wchar_t signedness.
12273 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12274 // memcmp always compares unsigned chars.
12275 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12276 }
12277 if (StopAtNull && !Char1.getInt())
12278 return Success(0, E);
12279 assert(!(StopAtNull && !Char2.getInt()))(static_cast <bool> (!(StopAtNull && !Char2.getInt
())) ? void (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())"
, "clang/lib/AST/ExprConstant.cpp", 12279, __extension__ __PRETTY_FUNCTION__
))
;
12280 if (!AdvanceElems())
12281 return false;
12282 }
12283 // We hit the strncmp / memcmp limit.
12284 return Success(0, E);
12285 }
12286
12287 case Builtin::BI__atomic_always_lock_free:
12288 case Builtin::BI__atomic_is_lock_free:
12289 case Builtin::BI__c11_atomic_is_lock_free: {
12290 APSInt SizeVal;
12291 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12292 return false;
12293
12294 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12295 // of two less than or equal to the maximum inline atomic width, we know it
12296 // is lock-free. If the size isn't a power of two, or greater than the
12297 // maximum alignment where we promote atomics, we know it is not lock-free
12298 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12299 // the answer can only be determined at runtime; for example, 16-byte
12300 // atomics have lock-free implementations on some, but not all,
12301 // x86-64 processors.
12302
12303 // Check power-of-two.
12304 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12305 if (Size.isPowerOfTwo()) {
12306 // Check against inlining width.
12307 unsigned InlineWidthBits =
12308 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12309 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12310 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12311 Size == CharUnits::One() ||
12312 E->getArg(1)->isNullPointerConstant(Info.Ctx,
12313 Expr::NPC_NeverValueDependent))
12314 // OK, we will inline appropriately-aligned operations of this size,
12315 // and _Atomic(T) is appropriately-aligned.
12316 return Success(1, E);
12317
12318 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12319 castAs<PointerType>()->getPointeeType();
12320 if (!PointeeType->isIncompleteType() &&
12321 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12322 // OK, we will inline operations on this object.
12323 return Success(1, E);
12324 }
12325 }
12326 }
12327
12328 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12329 Success(0, E) : Error(E);
12330 }
12331 case Builtin::BI__builtin_add_overflow:
12332 case Builtin::BI__builtin_sub_overflow:
12333 case Builtin::BI__builtin_mul_overflow:
12334 case Builtin::BI__builtin_sadd_overflow:
12335 case Builtin::BI__builtin_uadd_overflow:
12336 case Builtin::BI__builtin_uaddl_overflow:
12337 case Builtin::BI__builtin_uaddll_overflow:
12338 case Builtin::BI__builtin_usub_overflow:
12339 case Builtin::BI__builtin_usubl_overflow:
12340 case Builtin::BI__builtin_usubll_overflow:
12341 case Builtin::BI__builtin_umul_overflow:
12342 case Builtin::BI__builtin_umull_overflow:
12343 case Builtin::BI__builtin_umulll_overflow:
12344 case Builtin::BI__builtin_saddl_overflow:
12345 case Builtin::BI__builtin_saddll_overflow:
12346 case Builtin::BI__builtin_ssub_overflow:
12347 case Builtin::BI__builtin_ssubl_overflow:
12348 case Builtin::BI__builtin_ssubll_overflow:
12349 case Builtin::BI__builtin_smul_overflow:
12350 case Builtin::BI__builtin_smull_overflow:
12351 case Builtin::BI__builtin_smulll_overflow: {
12352 LValue ResultLValue;
12353 APSInt LHS, RHS;
12354
12355 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12356 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12357 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12358 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12359 return false;
12360
12361 APSInt Result;
12362 bool DidOverflow = false;
12363
12364 // If the types don't have to match, enlarge all 3 to the largest of them.
12365 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12366 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12367 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12368 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12369 ResultType->isSignedIntegerOrEnumerationType();
12370 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12371 ResultType->isSignedIntegerOrEnumerationType();
12372 uint64_t LHSSize = LHS.getBitWidth();
12373 uint64_t RHSSize = RHS.getBitWidth();
12374 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12375 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12376
12377 // Add an additional bit if the signedness isn't uniformly agreed to. We
12378 // could do this ONLY if there is a signed and an unsigned that both have
12379 // MaxBits, but the code to check that is pretty nasty. The issue will be
12380 // caught in the shrink-to-result later anyway.
12381 if (IsSigned && !AllSigned)
12382 ++MaxBits;
12383
12384 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12385 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12386 Result = APSInt(MaxBits, !IsSigned);
12387 }
12388
12389 // Find largest int.
12390 switch (BuiltinOp) {
12391 default:
12392 llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp"
, "clang/lib/AST/ExprConstant.cpp", 12392)
;
12393 case Builtin::BI__builtin_add_overflow:
12394 case Builtin::BI__builtin_sadd_overflow:
12395 case Builtin::BI__builtin_saddl_overflow:
12396 case Builtin::BI__builtin_saddll_overflow:
12397 case Builtin::BI__builtin_uadd_overflow:
12398 case Builtin::BI__builtin_uaddl_overflow:
12399 case Builtin::BI__builtin_uaddll_overflow:
12400 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12401 : LHS.uadd_ov(RHS, DidOverflow);
12402 break;
12403 case Builtin::BI__builtin_sub_overflow:
12404 case Builtin::BI__builtin_ssub_overflow:
12405 case Builtin::BI__builtin_ssubl_overflow:
12406 case Builtin::BI__builtin_ssubll_overflow:
12407 case Builtin::BI__builtin_usub_overflow:
12408 case Builtin::BI__builtin_usubl_overflow:
12409 case Builtin::BI__builtin_usubll_overflow:
12410 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12411 : LHS.usub_ov(RHS, DidOverflow);
12412 break;
12413 case Builtin::BI__builtin_mul_overflow:
12414 case Builtin::BI__builtin_smul_overflow:
12415 case Builtin::BI__builtin_smull_overflow:
12416 case Builtin::BI__builtin_smulll_overflow:
12417 case Builtin::BI__builtin_umul_overflow:
12418 case Builtin::BI__builtin_umull_overflow:
12419 case Builtin::BI__builtin_umulll_overflow:
12420 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12421 : LHS.umul_ov(RHS, DidOverflow);
12422 break;
12423 }
12424
12425 // In the case where multiple sizes are allowed, truncate and see if
12426 // the values are the same.
12427 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12428 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12429 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12430 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12431 // since it will give us the behavior of a TruncOrSelf in the case where
12432 // its parameter <= its size. We previously set Result to be at least the
12433 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12434 // will work exactly like TruncOrSelf.
12435 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12436 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12437
12438 if (!APSInt::isSameValue(Temp, Result))
12439 DidOverflow = true;
12440 Result = Temp;
12441 }
12442
12443 APValue APV{Result};
12444 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12445 return false;
12446 return Success(DidOverflow, E);
12447 }
12448 }
12449}
12450
12451/// Determine whether this is a pointer past the end of the complete
12452/// object referred to by the lvalue.
12453static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12454 const LValue &LV) {
12455 // A null pointer can be viewed as being "past the end" but we don't
12456 // choose to look at it that way here.
12457 if (!LV.getLValueBase())
12458 return false;
12459
12460 // If the designator is valid and refers to a subobject, we're not pointing
12461 // past the end.
12462 if (!LV.getLValueDesignator().Invalid &&
12463 !LV.getLValueDesignator().isOnePastTheEnd())
12464 return false;
12465
12466 // A pointer to an incomplete type might be past-the-end if the type's size is
12467 // zero. We cannot tell because the type is incomplete.
12468 QualType Ty = getType(LV.getLValueBase());
12469 if (Ty->isIncompleteType())
12470 return true;
12471
12472 // We're a past-the-end pointer if we point to the byte after the object,
12473 // no matter what our type or path is.
12474 auto Size = Ctx.getTypeSizeInChars(Ty);
12475 return LV.getLValueOffset() == Size;
12476}
12477
12478namespace {
12479
12480/// Data recursive integer evaluator of certain binary operators.
12481///
12482/// We use a data recursive algorithm for binary operators so that we are able
12483/// to handle extreme cases of chained binary operators without causing stack
12484/// overflow.
12485class DataRecursiveIntBinOpEvaluator {
12486 struct EvalResult {
12487 APValue Val;
12488 bool Failed;
12489
12490 EvalResult() : Failed(false) { }
12491
12492 void swap(EvalResult &RHS) {
12493 Val.swap(RHS.Val);
12494 Failed = RHS.Failed;
12495 RHS.Failed = false;
12496 }
12497 };
12498
12499 struct Job {
12500 const Expr *E;
12501 EvalResult LHSResult; // meaningful only for binary operator expression.
12502 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12503
12504 Job() = default;
12505 Job(Job &&) = default;
12506
12507 void startSpeculativeEval(EvalInfo &Info) {
12508 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12509 }
12510
12511 private:
12512 SpeculativeEvaluationRAII SpecEvalRAII;
12513 };
12514
12515 SmallVector<Job, 16> Queue;
12516
12517 IntExprEvaluator &IntEval;
12518 EvalInfo &Info;
12519 APValue &FinalResult;
12520
12521public:
12522 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12523 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12524
12525 /// True if \param E is a binary operator that we are going to handle
12526 /// data recursively.
12527 /// We handle binary operators that are comma, logical, or that have operands
12528 /// with integral or enumeration type.
12529 static bool shouldEnqueue(const BinaryOperator *E) {
12530 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12531 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12532 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12533 E->getRHS()->getType()->isIntegralOrEnumerationType());
12534 }
12535
12536 bool Traverse(const BinaryOperator *E) {
12537 enqueue(E);
12538 EvalResult PrevResult;
12539 while (!Queue.empty())
12540 process(PrevResult);
12541
12542 if (PrevResult.Failed) return false;
12543
12544 FinalResult.swap(PrevResult.Val);
12545 return true;
12546 }
12547
12548private:
12549 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12550 return IntEval.Success(Value, E, Result);
12551 }
12552 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12553 return IntEval.Success(Value, E, Result);
12554 }
12555 bool Error(const Expr *E) {
12556 return IntEval.Error(E);
12557 }
12558 bool Error(const Expr *E, diag::kind D) {
12559 return IntEval.Error(E, D);
12560 }
12561
12562 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12563 return Info.CCEDiag(E, D);
12564 }
12565
12566 // Returns true if visiting the RHS is necessary, false otherwise.
12567 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12568 bool &SuppressRHSDiags);
12569
12570 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12571 const BinaryOperator *E, APValue &Result);
12572
12573 void EvaluateExpr(const Expr *E, EvalResult &Result) {
12574 Result.Failed = !Evaluate(Result.Val, Info, E);
12575 if (Result.Failed)
12576 Result.Val = APValue();
12577 }
12578
12579 void process(EvalResult &Result);
12580
12581 void enqueue(const Expr *E) {
12582 E = E->IgnoreParens();
12583 Queue.resize(Queue.size()+1);
12584 Queue.back().E = E;
12585 Queue.back().Kind = Job::AnyExprKind;
12586 }
12587};
12588
12589}
12590
12591bool DataRecursiveIntBinOpEvaluator::
12592 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12593 bool &SuppressRHSDiags) {
12594 if (E->getOpcode() == BO_Comma) {
12595 // Ignore LHS but note if we could not evaluate it.
12596 if (LHSResult.Failed)
12597 return Info.noteSideEffect();
12598 return true;
12599 }
12600
12601 if (E->isLogicalOp()) {
12602 bool LHSAsBool;
12603 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12604 // We were able to evaluate the LHS, see if we can get away with not
12605 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12606 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12607 Success(LHSAsBool, E, LHSResult.Val);
12608 return false; // Ignore RHS
12609 }
12610 } else {
12611 LHSResult.Failed = true;
12612
12613 // Since we weren't able to evaluate the left hand side, it
12614 // might have had side effects.
12615 if (!Info.noteSideEffect())
12616 return false;
12617
12618 // We can't evaluate the LHS; however, sometimes the result
12619 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12620 // Don't ignore RHS and suppress diagnostics from this arm.
12621 SuppressRHSDiags = true;
12622 }
12623
12624 return true;
12625 }
12626
12627 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", 12628, __extension__ __PRETTY_FUNCTION__
))
12628 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", 12628, __extension__ __PRETTY_FUNCTION__
))
;
12629
12630 if (LHSResult.Failed && !Info.noteFailure())
12631 return false; // Ignore RHS;
12632
12633 return true;
12634}
12635
12636static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12637 bool IsSub) {
12638 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12639 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12640 // offsets.
12641 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", 12641, __extension__ __PRETTY_FUNCTION__
))
;
12642 CharUnits &Offset = LVal.getLValueOffset();
12643 uint64_t Offset64 = Offset.getQuantity();
12644 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12645 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12646 : Offset64 + Index64);
12647}
12648
12649bool DataRecursiveIntBinOpEvaluator::
12650 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12651 const BinaryOperator *E, APValue &Result) {
12652 if (E->getOpcode() == BO_Comma) {
12653 if (RHSResult.Failed)
12654 return false;
12655 Result = RHSResult.Val;
12656 return true;
12657 }
12658
12659 if (E->isLogicalOp()) {
12660 bool lhsResult, rhsResult;
12661 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12662 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12663
12664 if (LHSIsOK) {
12665 if (RHSIsOK) {
12666 if (E->getOpcode() == BO_LOr)
12667 return Success(lhsResult || rhsResult, E, Result);
12668 else
12669 return Success(lhsResult && rhsResult, E, Result);
12670 }
12671 } else {
12672 if (RHSIsOK) {
12673 // We can't evaluate the LHS; however, sometimes the result
12674 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12675 if (rhsResult == (E->getOpcode() == BO_LOr))
12676 return Success(rhsResult, E, Result);
12677 }
12678 }
12679
12680 return false;
12681 }
12682
12683 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", 12684, __extension__ __PRETTY_FUNCTION__
))
12684 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", 12684, __extension__ __PRETTY_FUNCTION__
))
;
12685
12686 if (LHSResult.Failed || RHSResult.Failed)
12687 return false;
12688
12689 const APValue &LHSVal = LHSResult.Val;
12690 const APValue &RHSVal = RHSResult.Val;
12691
12692 // Handle cases like (unsigned long)&a + 4.
12693 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12694 Result = LHSVal;
12695 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12696 return true;
12697 }
12698
12699 // Handle cases like 4 + (unsigned long)&a
12700 if (E->getOpcode() == BO_Add &&
12701 RHSVal.isLValue() && LHSVal.isInt()) {
12702 Result = RHSVal;
12703 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12704 return true;
12705 }
12706
12707 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12708 // Handle (intptr_t)&&A - (intptr_t)&&B.
12709 if (!LHSVal.getLValueOffset().isZero() ||
12710 !RHSVal.getLValueOffset().isZero())
12711 return false;
12712 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12713 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12714 if (!LHSExpr || !RHSExpr)
12715 return false;
12716 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12717 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12718 if (!LHSAddrExpr || !RHSAddrExpr)
12719 return false;
12720 // Make sure both labels come from the same function.
12721 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12722 RHSAddrExpr->getLabel()->getDeclContext())
12723 return false;
12724 Result = APValue(LHSAddrExpr, RHSAddrExpr);
12725 return true;
12726 }
12727
12728 // All the remaining cases expect both operands to be an integer
12729 if (!LHSVal.isInt() || !RHSVal.isInt())
12730 return Error(E);
12731
12732 // Set up the width and signedness manually, in case it can't be deduced
12733 // from the operation we're performing.
12734 // FIXME: Don't do this in the cases where we can deduce it.
12735 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12736 E->getType()->isUnsignedIntegerOrEnumerationType());
12737 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12738 RHSVal.getInt(), Value))
12739 return false;
12740 return Success(Value, E, Result);
12741}
12742
12743void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12744 Job &job = Queue.back();
12745
12746 switch (job.Kind) {
12747 case Job::AnyExprKind: {
12748 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12749 if (shouldEnqueue(Bop)) {
12750 job.Kind = Job::BinOpKind;
12751 enqueue(Bop->getLHS());
12752 return;
12753 }
12754 }
12755
12756 EvaluateExpr(job.E, Result);
12757 Queue.pop_back();
12758 return;
12759 }
12760
12761 case Job::BinOpKind: {
12762 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12763 bool SuppressRHSDiags = false;
12764 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12765 Queue.pop_back();
12766 return;
12767 }
12768 if (SuppressRHSDiags)
12769 job.startSpeculativeEval(Info);
12770 job.LHSResult.swap(Result);
12771 job.Kind = Job::BinOpVisitedLHSKind;
12772 enqueue(Bop->getRHS());
12773 return;
12774 }
12775
12776 case Job::BinOpVisitedLHSKind: {
12777 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12778 EvalResult RHS;
12779 RHS.swap(Result);
12780 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12781 Queue.pop_back();
12782 return;
12783 }
12784 }
12785
12786 llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "clang/lib/AST/ExprConstant.cpp"
, 12786)
;
12787}
12788
12789namespace {
12790enum class CmpResult {
12791 Unequal,
12792 Less,
12793 Equal,
12794 Greater,
12795 Unordered,
12796};
12797}
12798
12799template <class SuccessCB, class AfterCB>
12800static bool
12801EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12802 SuccessCB &&Success, AfterCB &&DoAfter) {
12803 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 12803, __extension__ __PRETTY_FUNCTION__))
;
12804 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", 12804, __extension__ __PRETTY_FUNCTION__
))
;
12805 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", 12807, __extension__ __PRETTY_FUNCTION__
))
12806 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", 12807, __extension__ __PRETTY_FUNCTION__
))
12807 "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", 12807, __extension__ __PRETTY_FUNCTION__
))
;
12808 auto Error = [&](const Expr *E) {
12809 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12810 return false;
12811 };
12812
12813 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12814 bool IsEquality = E->isEqualityOp();
12815
12816 QualType LHSTy = E->getLHS()->getType();
12817 QualType RHSTy = E->getRHS()->getType();
12818
12819 if (LHSTy->isIntegralOrEnumerationType() &&
12820 RHSTy->isIntegralOrEnumerationType()) {
12821 APSInt LHS, RHS;
12822 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12823 if (!LHSOK && !Info.noteFailure())
12824 return false;
12825 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12826 return false;
12827 if (LHS < RHS)
12828 return Success(CmpResult::Less, E);
12829 if (LHS > RHS)
12830 return Success(CmpResult::Greater, E);
12831 return Success(CmpResult::Equal, E);
12832 }
12833
12834 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12835 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12836 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12837
12838 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12839 if (!LHSOK && !Info.noteFailure())
12840 return false;
12841 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12842 return false;
12843 if (LHSFX < RHSFX)
12844 return Success(CmpResult::Less, E);
12845 if (LHSFX > RHSFX)
12846 return Success(CmpResult::Greater, E);
12847 return Success(CmpResult::Equal, E);
12848 }
12849
12850 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12851 ComplexValue LHS, RHS;
12852 bool LHSOK;
12853 if (E->isAssignmentOp()) {
12854 LValue LV;
12855 EvaluateLValue(E->getLHS(), LV, Info);
12856 LHSOK = false;
12857 } else if (LHSTy->isRealFloatingType()) {
12858 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12859 if (LHSOK) {
12860 LHS.makeComplexFloat();
12861 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12862 }
12863 } else {
12864 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12865 }
12866 if (!LHSOK && !Info.noteFailure())
12867 return false;
12868
12869 if (E->getRHS()->getType()->isRealFloatingType()) {
12870 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12871 return false;
12872 RHS.makeComplexFloat();
12873 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12874 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12875 return false;
12876
12877 if (LHS.isComplexFloat()) {
12878 APFloat::cmpResult CR_r =
12879 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12880 APFloat::cmpResult CR_i =
12881 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12882 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12883 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12884 } else {
12885 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", 12885, __extension__ __PRETTY_FUNCTION__
))
;
12886 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12887 LHS.getComplexIntImag() == RHS.getComplexIntImag();
12888 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12889 }
12890 }
12891
12892 if (LHSTy->isRealFloatingType() &&
12893 RHSTy->isRealFloatingType()) {
12894 APFloat RHS(0.0), LHS(0.0);
12895
12896 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12897 if (!LHSOK && !Info.noteFailure())
12898 return false;
12899
12900 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12901 return false;
12902
12903 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", 12903, __extension__ __PRETTY_FUNCTION__
))
;
12904 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12905 if (!Info.InConstantContext &&
12906 APFloatCmpResult == APFloat::cmpUnordered &&
12907 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12908 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12909 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12910 return false;
12911 }
12912 auto GetCmpRes = [&]() {
12913 switch (APFloatCmpResult) {
12914 case APFloat::cmpEqual:
12915 return CmpResult::Equal;
12916 case APFloat::cmpLessThan:
12917 return CmpResult::Less;
12918 case APFloat::cmpGreaterThan:
12919 return CmpResult::Greater;
12920 case APFloat::cmpUnordered:
12921 return CmpResult::Unordered;
12922 }
12923 llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum"
, "clang/lib/AST/ExprConstant.cpp", 12923)
;
12924 };
12925 return Success(GetCmpRes(), E);
12926 }
12927
12928 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12929 LValue LHSValue, RHSValue;
12930
12931 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12932 if (!LHSOK && !Info.noteFailure())
12933 return false;
12934
12935 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12936 return false;
12937
12938 // Reject differing bases from the normal codepath; we special-case
12939 // comparisons to null.
12940 if (!HasSameBase(LHSValue, RHSValue)) {
12941 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
12942 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
12943 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
12944 Info.FFDiag(E, DiagID)
12945 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
12946 return false;
12947 };
12948 // Inequalities and subtractions between unrelated pointers have
12949 // unspecified or undefined behavior.
12950 if (!IsEquality)
12951 return DiagComparison(
12952 diag::note_constexpr_pointer_comparison_unspecified);
12953 // A constant address may compare equal to the address of a symbol.
12954 // The one exception is that address of an object cannot compare equal
12955 // to a null pointer constant.
12956 // TODO: Should we restrict this to actual null pointers, and exclude the
12957 // case of zero cast to pointer type?
12958 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12959 (!RHSValue.Base && !RHSValue.Offset.isZero()))
12960 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
12961 !RHSValue.Base);
12962 // It's implementation-defined whether distinct literals will have
12963 // distinct addresses. In clang, the result of such a comparison is
12964 // unspecified, so it is not a constant expression. However, we do know
12965 // that the address of a literal will be non-null.
12966 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12967 LHSValue.Base && RHSValue.Base)
12968 return DiagComparison(diag::note_constexpr_literal_comparison);
12969 // We can't tell whether weak symbols will end up pointing to the same
12970 // object.
12971 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12972 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
12973 !IsWeakLValue(LHSValue));
12974 // We can't compare the address of the start of one object with the
12975 // past-the-end address of another object, per C++ DR1652.
12976 if (LHSValue.Base && LHSValue.Offset.isZero() &&
12977 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
12978 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
12979 true);
12980 if (RHSValue.Base && RHSValue.Offset.isZero() &&
12981 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
12982 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
12983 false);
12984 // We can't tell whether an object is at the same address as another
12985 // zero sized object.
12986 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12987 (LHSValue.Base && isZeroSized(RHSValue)))
12988 return DiagComparison(
12989 diag::note_constexpr_pointer_comparison_zero_sized);
12990 return Success(CmpResult::Unequal, E);
12991 }
12992
12993 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12994 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12995
12996 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12997 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12998
12999 // C++11 [expr.rel]p3:
13000 // Pointers to void (after pointer conversions) can be compared, with a
13001 // result defined as follows: If both pointers represent the same
13002 // address or are both the null pointer value, the result is true if the
13003 // operator is <= or >= and false otherwise; otherwise the result is
13004 // unspecified.
13005 // We interpret this as applying to pointers to *cv* void.
13006 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13007 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13008
13009 // C++11 [expr.rel]p2:
13010 // - If two pointers point to non-static data members of the same object,
13011 // or to subobjects or array elements fo such members, recursively, the
13012 // pointer to the later declared member compares greater provided the
13013 // two members have the same access control and provided their class is
13014 // not a union.
13015 // [...]
13016 // - Otherwise pointer comparisons are unspecified.
13017 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13018 bool WasArrayIndex;
13019 unsigned Mismatch = FindDesignatorMismatch(
13020 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13021 // At the point where the designators diverge, the comparison has a
13022 // specified value if:
13023 // - we are comparing array indices
13024 // - we are comparing fields of a union, or fields with the same access
13025 // Otherwise, the result is unspecified and thus the comparison is not a
13026 // constant expression.
13027 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13028 Mismatch < RHSDesignator.Entries.size()) {
13029 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13030 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13031 if (!LF && !RF)
13032 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13033 else if (!LF)
13034 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13035 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13036 << RF->getParent() << RF;
13037 else if (!RF)
13038 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13039 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13040 << LF->getParent() << LF;
13041 else if (!LF->getParent()->isUnion() &&
13042 LF->getAccess() != RF->getAccess())
13043 Info.CCEDiag(E,
13044 diag::note_constexpr_pointer_comparison_differing_access)
13045 << LF << LF->getAccess() << RF << RF->getAccess()
13046 << LF->getParent();
13047 }
13048 }
13049
13050 // The comparison here must be unsigned, and performed with the same
13051 // width as the pointer.
13052 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13053 uint64_t CompareLHS = LHSOffset.getQuantity();
13054 uint64_t CompareRHS = RHSOffset.getQuantity();
13055 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", 13055, __extension__ __PRETTY_FUNCTION__
))
;
13056 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13057 CompareLHS &= Mask;
13058 CompareRHS &= Mask;
13059
13060 // If there is a base and this is a relational operator, we can only
13061 // compare pointers within the object in question; otherwise, the result
13062 // depends on where the object is located in memory.
13063 if (!LHSValue.Base.isNull() && IsRelational) {
13064 QualType BaseTy = getType(LHSValue.Base);
13065 if (BaseTy->isIncompleteType())
13066 return Error(E);
13067 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13068 uint64_t OffsetLimit = Size.getQuantity();
13069 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13070 return Error(E);
13071 }
13072
13073 if (CompareLHS < CompareRHS)
13074 return Success(CmpResult::Less, E);
13075 if (CompareLHS > CompareRHS)
13076 return Success(CmpResult::Greater, E);
13077 return Success(CmpResult::Equal, E);
13078 }
13079
13080 if (LHSTy->isMemberPointerType()) {
13081 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", 13081, __extension__ __PRETTY_FUNCTION__
))
;
13082 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", 13082, __extension__ __PRETTY_FUNCTION__
))
;
13083
13084 MemberPtr LHSValue, RHSValue;
13085
13086 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13087 if (!LHSOK && !Info.noteFailure())
13088 return false;
13089
13090 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13091 return false;
13092
13093 // If either operand is a pointer to a weak function, the comparison is not
13094 // constant.
13095 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13096 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13097 << LHSValue.getDecl();
13098 return true;
13099 }
13100 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13101 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13102 << RHSValue.getDecl();
13103 return true;
13104 }
13105
13106 // C++11 [expr.eq]p2:
13107 // If both operands are null, they compare equal. Otherwise if only one is
13108 // null, they compare unequal.
13109 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13110 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13111 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13112 }
13113
13114 // Otherwise if either is a pointer to a virtual member function, the
13115 // result is unspecified.
13116 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13117 if (MD->isVirtual())
13118 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13120 if (MD->isVirtual())
13121 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13122
13123 // Otherwise they compare equal if and only if they would refer to the
13124 // same member of the same most derived object or the same subobject if
13125 // they were dereferenced with a hypothetical object of the associated
13126 // class type.
13127 bool Equal = LHSValue == RHSValue;
13128 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13129 }
13130
13131 if (LHSTy->isNullPtrType()) {
13132 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", 13132, __extension__ __PRETTY_FUNCTION__
))
;
13133 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", 13133, __extension__ __PRETTY_FUNCTION__
))
;
13134 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13135 // are compared, the result is true of the operator is <=, >= or ==, and
13136 // false otherwise.
13137 return Success(CmpResult::Equal, E);
13138 }
13139
13140 return DoAfter();
13141}
13142
13143bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13144 if (!CheckLiteralType(Info, E))
13145 return false;
13146
13147 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13148 ComparisonCategoryResult CCR;
13149 switch (CR) {
13150 case CmpResult::Unequal:
13151 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", 13151)
;
13152 case CmpResult::Less:
13153 CCR = ComparisonCategoryResult::Less;
13154 break;
13155 case CmpResult::Equal:
13156 CCR = ComparisonCategoryResult::Equal;
13157 break;
13158 case CmpResult::Greater:
13159 CCR = ComparisonCategoryResult::Greater;
13160 break;
13161 case CmpResult::Unordered:
13162 CCR = ComparisonCategoryResult::Unordered;
13163 break;
13164 }
13165 // Evaluation succeeded. Lookup the information for the comparison category
13166 // type and fetch the VarDecl for the result.
13167 const ComparisonCategoryInfo &CmpInfo =
13168 Info.Ctx.CompCategories.getInfoForType(E->getType());
13169 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13170 // Check and evaluate the result as a constant expression.
13171 LValue LV;
13172 LV.set(VD);
13173 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13174 return false;
13175 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13176 ConstantExprKind::Normal);
13177 };
13178 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13179 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13180 });
13181}
13182
13183bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13184 // We don't support assignment in C. C++ assignments don't get here because
13185 // assignment is an lvalue in C++.
13186 if (E->isAssignmentOp()) {
13187 Error(E);
13188 if (!Info.noteFailure())
13189 return false;
13190 }
13191
13192 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13193 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13194
13195 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", 13197, __extension__ __PRETTY_FUNCTION__
))
13196 !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", 13197, __extension__ __PRETTY_FUNCTION__
))
13197 "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", 13197, __extension__ __PRETTY_FUNCTION__
))
;
13198
13199 if (E->isComparisonOp()) {
13200 // Evaluate builtin binary comparisons by evaluating them as three-way
13201 // comparisons and then translating the result.
13202 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13203 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", 13204, __extension__ __PRETTY_FUNCTION__
))
13204 "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", 13204, __extension__ __PRETTY_FUNCTION__
))
;
13205 bool IsEqual = CR == CmpResult::Equal,
13206 IsLess = CR == CmpResult::Less,
13207 IsGreater = CR == CmpResult::Greater;
13208 auto Op = E->getOpcode();
13209 switch (Op) {
13210 default:
13211 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "clang/lib/AST/ExprConstant.cpp", 13211)
;
13212 case BO_EQ:
13213 case BO_NE:
13214 return Success(IsEqual == (Op == BO_EQ), E);
13215 case BO_LT:
13216 return Success(IsLess, E);
13217 case BO_GT:
13218 return Success(IsGreater, E);
13219 case BO_LE:
13220 return Success(IsEqual || IsLess, E);
13221 case BO_GE:
13222 return Success(IsEqual || IsGreater, E);
13223 }
13224 };
13225 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13226 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13227 });
13228 }
13229
13230 QualType LHSTy = E->getLHS()->getType();
13231 QualType RHSTy = E->getRHS()->getType();
13232
13233 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13234 E->getOpcode() == BO_Sub) {
13235 LValue LHSValue, RHSValue;
13236
13237 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13238 if (!LHSOK && !Info.noteFailure())
13239 return false;
13240
13241 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13242 return false;
13243
13244 // Reject differing bases from the normal codepath; we special-case
13245 // comparisons to null.
13246 if (!HasSameBase(LHSValue, RHSValue)) {
13247 // Handle &&A - &&B.
13248 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13249 return Error(E);
13250 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13251 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13252 if (!LHSExpr || !RHSExpr)
13253 return Error(E);
13254 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13255 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13256 if (!LHSAddrExpr || !RHSAddrExpr)
13257 return Error(E);
13258 // Make sure both labels come from the same function.
13259 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13260 RHSAddrExpr->getLabel()->getDeclContext())
13261 return Error(E);
13262 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13263 }
13264 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13265 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13266
13267 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13268 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13269
13270 // C++11 [expr.add]p6:
13271 // Unless both pointers point to elements of the same array object, or
13272 // one past the last element of the array object, the behavior is
13273 // undefined.
13274 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13275 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13276 RHSDesignator))
13277 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13278
13279 QualType Type = E->getLHS()->getType();
13280 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13281
13282 CharUnits ElementSize;
13283 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13284 return false;
13285
13286 // As an extension, a type may have zero size (empty struct or union in
13287 // C, array of zero length). Pointer subtraction in such cases has
13288 // undefined behavior, so is not constant.
13289 if (ElementSize.isZero()) {
13290 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13291 << ElementType;
13292 return false;
13293 }
13294
13295 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13296 // and produce incorrect results when it overflows. Such behavior
13297 // appears to be non-conforming, but is common, so perhaps we should
13298 // assume the standard intended for such cases to be undefined behavior
13299 // and check for them.
13300
13301 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13302 // overflow in the final conversion to ptrdiff_t.
13303 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13304 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13305 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13306 false);
13307 APSInt TrueResult = (LHS - RHS) / ElemSize;
13308 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13309
13310 if (Result.extend(65) != TrueResult &&
13311 !HandleOverflow(Info, E, TrueResult, E->getType()))
13312 return false;
13313 return Success(Result, E);
13314 }
13315
13316 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13317}
13318
13319/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13320/// a result as the expression's type.
13321bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13322 const UnaryExprOrTypeTraitExpr *E) {
13323 switch(E->getKind()) {
13324 case UETT_PreferredAlignOf:
13325 case UETT_AlignOf: {
13326 if (E->isArgumentType())
13327 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13328 E);
13329 else
13330 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13331 E);
13332 }
13333
13334 case UETT_VecStep: {
13335 QualType Ty = E->getTypeOfArgument();
13336
13337 if (Ty->isVectorType()) {
13338 unsigned n = Ty->castAs<VectorType>()->getNumElements();
13339
13340 // The vec_step built-in functions that take a 3-component
13341 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13342 if (n == 3)
13343 n = 4;
13344
13345 return Success(n, E);
13346 } else
13347 return Success(1, E);
13348 }
13349
13350 case UETT_SizeOf: {
13351 QualType SrcTy = E->getTypeOfArgument();
13352 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13353 // the result is the size of the referenced type."
13354 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13355 SrcTy = Ref->getPointeeType();
13356
13357 CharUnits Sizeof;
13358 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13359 return false;
13360 return Success(Sizeof, E);
13361 }
13362 case UETT_OpenMPRequiredSimdAlign:
13363 assert(E->isArgumentType())(static_cast <bool> (E->isArgumentType()) ? void (0)
: __assert_fail ("E->isArgumentType()", "clang/lib/AST/ExprConstant.cpp"
, 13363, __extension__ __PRETTY_FUNCTION__))
;
13364 return Success(
13365 Info.Ctx.toCharUnitsFromBits(
13366 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13367 .getQuantity(),
13368 E);
13369 }
13370
13371 llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "clang/lib/AST/ExprConstant.cpp"
, 13371)
;
13372}
13373
13374bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13375 CharUnits Result;
13376 unsigned n = OOE->getNumComponents();
13377 if (n == 0)
13378 return Error(OOE);
13379 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13380 for (unsigned i = 0; i != n; ++i) {
13381 OffsetOfNode ON = OOE->getComponent(i);
13382 switch (ON.getKind()) {
13383 case OffsetOfNode::Array: {
13384 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13385 APSInt IdxResult;
13386 if (!EvaluateInteger(Idx, IdxResult, Info))
13387 return false;
13388 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13389 if (!AT)
13390 return Error(OOE);
13391 CurrentType = AT->getElementType();
13392 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13393 Result += IdxResult.getSExtValue() * ElementSize;
13394 break;
13395 }
13396
13397 case OffsetOfNode::Field: {
13398 FieldDecl *MemberDecl = ON.getField();
13399 const RecordType *RT = CurrentType->getAs<RecordType>();
13400 if (!RT)
13401 return Error(OOE);
13402 RecordDecl *RD = RT->getDecl();
13403 if (RD->isInvalidDecl()) return false;
13404 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13405 unsigned i = MemberDecl->getFieldIndex();
13406 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", 13406, __extension__ __PRETTY_FUNCTION__
))
;
13407 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13408 CurrentType = MemberDecl->getType().getNonReferenceType();
13409 break;
13410 }
13411
13412 case OffsetOfNode::Identifier:
13413 llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof"
, "clang/lib/AST/ExprConstant.cpp", 13413)
;
13414
13415 case OffsetOfNode::Base: {
13416 CXXBaseSpecifier *BaseSpec = ON.getBase();
13417 if (BaseSpec->isVirtual())
13418 return Error(OOE);
13419
13420 // Find the layout of the class whose base we are looking into.
13421 const RecordType *RT = CurrentType->getAs<RecordType>();
13422 if (!RT)
13423 return Error(OOE);
13424 RecordDecl *RD = RT->getDecl();
13425 if (RD->isInvalidDecl()) return false;
13426 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13427
13428 // Find the base class itself.
13429 CurrentType = BaseSpec->getType();
13430 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13431 if (!BaseRT)
13432 return Error(OOE);
13433
13434 // Add the offset to the base.
13435 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13436 break;
13437 }
13438 }
13439 }
13440 return Success(Result, OOE);
13441}
13442
13443bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13444 switch (E->getOpcode()) {
13445 default:
13446 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13447 // See C99 6.6p3.
13448 return Error(E);
13449 case UO_Extension:
13450 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13451 // If so, we could clear the diagnostic ID.
13452 return Visit(E->getSubExpr());
13453 case UO_Plus:
13454 // The result is just the value.
13455 return Visit(E->getSubExpr());
13456 case UO_Minus: {
13457 if (!Visit(E->getSubExpr()))
13458 return false;
13459 if (!Result.isInt()) return Error(E);
13460 const APSInt &Value = Result.getInt();
13461 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13462 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13463 E->getType()))
13464 return false;
13465 return Success(-Value, E);
13466 }
13467 case UO_Not: {
13468 if (!Visit(E->getSubExpr()))
13469 return false;
13470 if (!Result.isInt()) return Error(E);
13471 return Success(~Result.getInt(), E);
13472 }
13473 case UO_LNot: {
13474 bool bres;
13475 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13476 return false;
13477 return Success(!bres, E);
13478 }
13479 }
13480}
13481
13482/// HandleCast - This is used to evaluate implicit or explicit casts where the
13483/// result type is integer.
13484bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13485 const Expr *SubExpr = E->getSubExpr();
13486 QualType DestType = E->getType();
13487 QualType SrcType = SubExpr->getType();
13488
13489 switch (E->getCastKind()) {
13490 case CK_BaseToDerived:
13491 case CK_DerivedToBase:
13492 case CK_UncheckedDerivedToBase:
13493 case CK_Dynamic:
13494 case CK_ToUnion:
13495 case CK_ArrayToPointerDecay:
13496 case CK_FunctionToPointerDecay:
13497 case CK_NullToPointer:
13498 case CK_NullToMemberPointer:
13499 case CK_BaseToDerivedMemberPointer:
13500 case CK_DerivedToBaseMemberPointer:
13501 case CK_ReinterpretMemberPointer:
13502 case CK_ConstructorConversion:
13503 case CK_IntegralToPointer:
13504 case CK_ToVoid:
13505 case CK_VectorSplat:
13506 case CK_IntegralToFloating:
13507 case CK_FloatingCast:
13508 case CK_CPointerToObjCPointerCast:
13509 case CK_BlockPointerToObjCPointerCast:
13510 case CK_AnyPointerToBlockPointerCast:
13511 case CK_ObjCObjectLValueCast:
13512 case CK_FloatingRealToComplex:
13513 case CK_FloatingComplexToReal:
13514 case CK_FloatingComplexCast:
13515 case CK_FloatingComplexToIntegralComplex:
13516 case CK_IntegralRealToComplex:
13517 case CK_IntegralComplexCast:
13518 case CK_IntegralComplexToFloatingComplex:
13519 case CK_BuiltinFnToFnPtr:
13520 case CK_ZeroToOCLOpaqueType:
13521 case CK_NonAtomicToAtomic:
13522 case CK_AddressSpaceConversion:
13523 case CK_IntToOCLSampler:
13524 case CK_FloatingToFixedPoint:
13525 case CK_FixedPointToFloating:
13526 case CK_FixedPointCast:
13527 case CK_IntegralToFixedPoint:
13528 case CK_MatrixCast:
13529 llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value"
, "clang/lib/AST/ExprConstant.cpp", 13529)
;
13530
13531 case CK_BitCast:
13532 case CK_Dependent:
13533 case CK_LValueBitCast:
13534 case CK_ARCProduceObject:
13535 case CK_ARCConsumeObject:
13536 case CK_ARCReclaimReturnedObject:
13537 case CK_ARCExtendBlockObject:
13538 case CK_CopyAndAutoreleaseBlockObject:
13539 return Error(E);
13540
13541 case CK_UserDefinedConversion:
13542 case CK_LValueToRValue:
13543 case CK_AtomicToNonAtomic:
13544 case CK_NoOp:
13545 case CK_LValueToRValueBitCast:
13546 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13547
13548 case CK_MemberPointerToBoolean:
13549 case CK_PointerToBoolean:
13550 case CK_IntegralToBoolean:
13551 case CK_FloatingToBoolean:
13552 case CK_BooleanToSignedIntegral:
13553 case CK_FloatingComplexToBoolean:
13554 case CK_IntegralComplexToBoolean: {
13555 bool BoolResult;
13556 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13557 return false;
13558 uint64_t IntResult = BoolResult;
13559 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13560 IntResult = (uint64_t)-1;
13561 return Success(IntResult, E);
13562 }
13563
13564 case CK_FixedPointToIntegral: {
13565 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13566 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13567 return false;
13568 bool Overflowed;
13569 llvm::APSInt Result = Src.convertToInt(
13570 Info.Ctx.getIntWidth(DestType),
13571 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13572 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13573 return false;
13574 return Success(Result, E);
13575 }
13576
13577 case CK_FixedPointToBoolean: {
13578 // Unsigned padding does not affect this.
13579 APValue Val;
13580 if (!Evaluate(Val, Info, SubExpr))
13581 return false;
13582 return Success(Val.getFixedPoint().getBoolValue(), E);
13583 }
13584
13585 case CK_IntegralCast: {
13586 if (!Visit(SubExpr))
13587 return false;
13588
13589 if (!Result.isInt()) {
13590 // Allow casts of address-of-label differences if they are no-ops
13591 // or narrowing. (The narrowing case isn't actually guaranteed to
13592 // be constant-evaluatable except in some narrow cases which are hard
13593 // to detect here. We let it through on the assumption the user knows
13594 // what they are doing.)
13595 if (Result.isAddrLabelDiff())
13596 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13597 // Only allow casts of lvalues if they are lossless.
13598 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13599 }
13600
13601 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13602 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13603 DestType->isEnumeralType()) {
13604
13605 bool ConstexprVar = true;
13606
13607 // We know if we are here that we are in a context that we might require
13608 // a constant expression or a context that requires a constant
13609 // value. But if we are initializing a value we don't know if it is a
13610 // constexpr variable or not. We can check the EvaluatingDecl to determine
13611 // if it constexpr or not. If not then we don't want to emit a diagnostic.
13612 if (const auto *VD = dyn_cast_or_null<VarDecl>(
13613 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13614 ConstexprVar = VD->isConstexpr();
13615
13616 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13617 const EnumDecl *ED = ET->getDecl();
13618 // Check that the value is within the range of the enumeration values.
13619 //
13620 // This corressponds to [expr.static.cast]p10 which says:
13621 // A value of integral or enumeration type can be explicitly converted
13622 // to a complete enumeration type ... If the enumeration type does not
13623 // have a fixed underlying type, the value is unchanged if the original
13624 // value is within the range of the enumeration values ([dcl.enum]), and
13625 // otherwise, the behavior is undefined.
13626 //
13627 // This was resolved as part of DR2338 which has CD5 status.
13628 if (!ED->isFixed()) {
13629 llvm::APInt Min;
13630 llvm::APInt Max;
13631
13632 ED->getValueRange(Max, Min);
13633 --Max;
13634
13635 if (ED->getNumNegativeBits() && ConstexprVar &&
13636 (Max.slt(Result.getInt().getSExtValue()) ||
13637 Min.sgt(Result.getInt().getSExtValue())))
13638 Info.Ctx.getDiagnostics().Report(
13639 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13640 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13641 << Max.getSExtValue();
13642 else if (!ED->getNumNegativeBits() && ConstexprVar &&
13643 Max.ult(Result.getInt().getZExtValue()))
13644 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13645 diag::warn_constexpr_unscoped_enum_out_of_range)
13646 << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
13647 }
13648 }
13649
13650 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13651 Result.getInt()), E);
13652 }
13653
13654 case CK_PointerToIntegral: {
13655 CCEDiag(E, diag::note_constexpr_invalid_cast)
13656 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13657
13658 LValue LV;
13659 if (!EvaluatePointer(SubExpr, LV, Info))
13660 return false;
13661
13662 if (LV.getLValueBase()) {
13663 // Only allow based lvalue casts if they are lossless.
13664 // FIXME: Allow a larger integer size than the pointer size, and allow
13665 // narrowing back down to pointer width in subsequent integral casts.
13666 // FIXME: Check integer type's active bits, not its type size.
13667 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13668 return Error(E);
13669
13670 LV.Designator.setInvalid();
13671 LV.moveInto(Result);
13672 return true;
13673 }
13674
13675 APSInt AsInt;
13676 APValue V;
13677 LV.moveInto(V);
13678 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13679 llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "clang/lib/AST/ExprConstant.cpp"
, 13679)
;
13680
13681 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13682 }
13683
13684 case CK_IntegralComplexToReal: {
13685 ComplexValue C;
13686 if (!EvaluateComplex(SubExpr, C, Info))
13687 return false;
13688 return Success(C.getComplexIntReal(), E);
13689 }
13690
13691 case CK_FloatingToIntegral: {
13692 APFloat F(0.0);
13693 if (!EvaluateFloat(SubExpr, F, Info))
13694 return false;
13695
13696 APSInt Value;
13697 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13698 return false;
13699 return Success(Value, E);
13700 }
13701 }
13702
13703 llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value"
, "clang/lib/AST/ExprConstant.cpp", 13703)
;
13704}
13705
13706bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13707 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13708 ComplexValue LV;
13709 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13710 return false;
13711 if (!LV.isComplexInt())
13712 return Error(E);
13713 return Success(LV.getComplexIntReal(), E);
13714 }
13715
13716 return Visit(E->getSubExpr());
13717}
13718
13719bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13720 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13721 ComplexValue LV;
13722 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13723 return false;
13724 if (!LV.isComplexInt())
13725 return Error(E);
13726 return Success(LV.getComplexIntImag(), E);
13727 }
13728
13729 VisitIgnoredValue(E->getSubExpr());
13730 return Success(0, E);
13731}
13732
13733bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13734 return Success(E->getPackLength(), E);
13735}
13736
13737bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13738 return Success(E->getValue(), E);
13739}
13740
13741bool IntExprEvaluator::VisitConceptSpecializationExpr(
13742 const ConceptSpecializationExpr *E) {
13743 return Success(E->isSatisfied(), E);
13744}
13745
13746bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13747 return Success(E->isSatisfied(), E);
13748}
13749
13750bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13751 switch (E->getOpcode()) {
13752 default:
13753 // Invalid unary operators
13754 return Error(E);
13755 case UO_Plus:
13756 // The result is just the value.
13757 return Visit(E->getSubExpr());
13758 case UO_Minus: {
13759 if (!Visit(E->getSubExpr())) return false;
13760 if (!Result.isFixedPoint())
13761 return Error(E);
13762 bool Overflowed;
13763 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13764 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13765 return false;
13766 return Success(Negated, E);
13767 }
13768 case UO_LNot: {
13769 bool bres;
13770 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13771 return false;
13772 return Success(!bres, E);
13773 }
13774 }
13775}
13776
13777bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13778 const Expr *SubExpr = E->getSubExpr();
13779 QualType DestType = E->getType();
13780 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", 13781, __extension__ __PRETTY_FUNCTION__
))
13781 "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", 13781, __extension__ __PRETTY_FUNCTION__
))
;
13782 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13783
13784 switch (E->getCastKind()) {
13785 case CK_FixedPointCast: {
13786 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13787 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13788 return false;
13789 bool Overflowed;
13790 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13791 if (Overflowed) {
13792 if (Info.checkingForUndefinedBehavior())
13793 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13794 diag::warn_fixedpoint_constant_overflow)
13795 << Result.toString() << E->getType();
13796 if (!HandleOverflow(Info, E, Result, E->getType()))
13797 return false;
13798 }
13799 return Success(Result, E);
13800 }
13801 case CK_IntegralToFixedPoint: {
13802 APSInt Src;
13803 if (!EvaluateInteger(SubExpr, Src, Info))
13804 return false;
13805
13806 bool Overflowed;
13807 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13808 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13809
13810 if (Overflowed) {
13811 if (Info.checkingForUndefinedBehavior())
13812 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13813 diag::warn_fixedpoint_constant_overflow)
13814 << IntResult.toString() << E->getType();
13815 if (!HandleOverflow(Info, E, IntResult, E->getType()))
13816 return false;
13817 }
13818
13819 return Success(IntResult, E);
13820 }
13821 case CK_FloatingToFixedPoint: {
13822 APFloat Src(0.0);
13823 if (!EvaluateFloat(SubExpr, Src, Info))
13824 return false;
13825
13826 bool Overflowed;
13827 APFixedPoint Result = APFixedPoint::getFromFloatValue(
13828 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13829
13830 if (Overflowed) {
13831 if (Info.checkingForUndefinedBehavior())
13832 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13833 diag::warn_fixedpoint_constant_overflow)
13834 << Result.toString() << E->getType();
13835 if (!HandleOverflow(Info, E, Result, E->getType()))
13836 return false;
13837 }
13838
13839 return Success(Result, E);
13840 }
13841 case CK_NoOp:
13842 case CK_LValueToRValue:
13843 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13844 default:
13845 return Error(E);
13846 }
13847}
13848
13849bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13850 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13851 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13852
13853 const Expr *LHS = E->getLHS();
13854 const Expr *RHS = E->getRHS();
13855 FixedPointSemantics ResultFXSema =
13856 Info.Ctx.getFixedPointSemantics(E->getType());
13857
13858 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13859 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13860 return false;
13861 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13862 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13863 return false;
13864
13865 bool OpOverflow = false, ConversionOverflow = false;
13866 APFixedPoint Result(LHSFX.getSemantics());
13867 switch (E->getOpcode()) {
13868 case BO_Add: {
13869 Result = LHSFX.add(RHSFX, &OpOverflow)
13870 .convert(ResultFXSema, &ConversionOverflow);
13871 break;
13872 }
13873 case BO_Sub: {
13874 Result = LHSFX.sub(RHSFX, &OpOverflow)
13875 .convert(ResultFXSema, &ConversionOverflow);
13876 break;
13877 }
13878 case BO_Mul: {
13879 Result = LHSFX.mul(RHSFX, &OpOverflow)
13880 .convert(ResultFXSema, &ConversionOverflow);
13881 break;
13882 }
13883 case BO_Div: {
13884 if (RHSFX.getValue() == 0) {
13885 Info.FFDiag(E, diag::note_expr_divide_by_zero);
13886 return false;
13887 }
13888 Result = LHSFX.div(RHSFX, &OpOverflow)
13889 .convert(ResultFXSema, &ConversionOverflow);
13890 break;
13891 }
13892 case BO_Shl:
13893 case BO_Shr: {
13894 FixedPointSemantics LHSSema = LHSFX.getSemantics();
13895 llvm::APSInt RHSVal = RHSFX.getValue();
13896
13897 unsigned ShiftBW =
13898 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13899 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13900 // Embedded-C 4.1.6.2.2:
13901 // The right operand must be nonnegative and less than the total number
13902 // of (nonpadding) bits of the fixed-point operand ...
13903 if (RHSVal.isNegative())
13904 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13905 else if (Amt != RHSVal)
13906 Info.CCEDiag(E, diag::note_constexpr_large_shift)
13907 << RHSVal << E->getType() << ShiftBW;
13908
13909 if (E->getOpcode() == BO_Shl)
13910 Result = LHSFX.shl(Amt, &OpOverflow);
13911 else
13912 Result = LHSFX.shr(Amt, &OpOverflow);
13913 break;
13914 }
13915 default:
13916 return false;
13917 }
13918 if (OpOverflow || ConversionOverflow) {
13919 if (Info.checkingForUndefinedBehavior())
13920 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13921 diag::warn_fixedpoint_constant_overflow)
13922 << Result.toString() << E->getType();
13923 if (!HandleOverflow(Info, E, Result, E->getType()))
13924 return false;
13925 }
13926 return Success(Result, E);
13927}
13928
13929//===----------------------------------------------------------------------===//
13930// Float Evaluation
13931//===----------------------------------------------------------------------===//
13932
13933namespace {
13934class FloatExprEvaluator
13935 : public ExprEvaluatorBase<FloatExprEvaluator> {
13936 APFloat &Result;
13937public:
13938 FloatExprEvaluator(EvalInfo &info, APFloat &result)
13939 : ExprEvaluatorBaseTy(info), Result(result) {}
13940
13941 bool Success(const APValue &V, const Expr *e) {
13942 Result = V.getFloat();
13943 return true;
13944 }
13945
13946 bool ZeroInitialization(const Expr *E) {
13947 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13948 return true;
13949 }
13950
13951 bool VisitCallExpr(const CallExpr *E);
13952
13953 bool VisitUnaryOperator(const UnaryOperator *E);
13954 bool VisitBinaryOperator(const BinaryOperator *E);
13955 bool VisitFloatingLiteral(const FloatingLiteral *E);
13956 bool VisitCastExpr(const CastExpr *E);
13957
13958 bool VisitUnaryReal(const UnaryOperator *E);
13959 bool VisitUnaryImag(const UnaryOperator *E);
13960
13961 // FIXME: Missing: array subscript of vector, member of vector
13962};
13963} // end anonymous namespace
13964
13965static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13966 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 13966, __extension__ __PRETTY_FUNCTION__))
;
13967 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", 13967, __extension__ __PRETTY_FUNCTION__
))
;
13968 return FloatExprEvaluator(Info, Result).Visit(E);
13969}
13970
13971static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13972 QualType ResultTy,
13973 const Expr *Arg,
13974 bool SNaN,
13975 llvm::APFloat &Result) {
13976 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13977 if (!S) return false;
13978
13979 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13980
13981 llvm::APInt fill;
13982
13983 // Treat empty strings as if they were zero.
13984 if (S->getString().empty())
13985 fill = llvm::APInt(32, 0);
13986 else if (S->getString().getAsInteger(0, fill))
13987 return false;
13988
13989 if (Context.getTargetInfo().isNan2008()) {
13990 if (SNaN)
13991 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13992 else
13993 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13994 } else {
13995 // Prior to IEEE 754-2008, architectures were allowed to choose whether
13996 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13997 // a different encoding to what became a standard in 2008, and for pre-
13998 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13999 // sNaN. This is now known as "legacy NaN" encoding.
14000 if (SNaN)
14001 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14002 else
14003 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14004 }
14005
14006 return true;
14007}
14008
14009bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14010 if (!IsConstantEvaluatedBuiltinCall(E))
14011 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14012
14013 switch (E->getBuiltinCallee()) {
14014 default:
14015 return false;
14016
14017 case Builtin::BI__builtin_huge_val:
14018 case Builtin::BI__builtin_huge_valf:
14019 case Builtin::BI__builtin_huge_vall:
14020 case Builtin::BI__builtin_huge_valf16:
14021 case Builtin::BI__builtin_huge_valf128:
14022 case Builtin::BI__builtin_inf:
14023 case Builtin::BI__builtin_inff:
14024 case Builtin::BI__builtin_infl:
14025 case Builtin::BI__builtin_inff16:
14026 case Builtin::BI__builtin_inff128: {
14027 const llvm::fltSemantics &Sem =
14028 Info.Ctx.getFloatTypeSemantics(E->getType());
14029 Result = llvm::APFloat::getInf(Sem);
14030 return true;
14031 }
14032
14033 case Builtin::BI__builtin_nans:
14034 case Builtin::BI__builtin_nansf:
14035 case Builtin::BI__builtin_nansl:
14036 case Builtin::BI__builtin_nansf16:
14037 case Builtin::BI__builtin_nansf128:
14038 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14039 true, Result))
14040 return Error(E);
14041 return true;
14042
14043 case Builtin::BI__builtin_nan:
14044 case Builtin::BI__builtin_nanf:
14045 case Builtin::BI__builtin_nanl:
14046 case Builtin::BI__builtin_nanf16:
14047 case Builtin::BI__builtin_nanf128:
14048 // If this is __builtin_nan() turn this into a nan, otherwise we
14049 // can't constant fold it.
14050 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14051 false, Result))
14052 return Error(E);
14053 return true;
14054
14055 case Builtin::BI__builtin_fabs:
14056 case Builtin::BI__builtin_fabsf:
14057 case Builtin::BI__builtin_fabsl:
14058 case Builtin::BI__builtin_fabsf128:
14059 // The C standard says "fabs raises no floating-point exceptions,
14060 // even if x is a signaling NaN. The returned value is independent of
14061 // the current rounding direction mode." Therefore constant folding can
14062 // proceed without regard to the floating point settings.
14063 // Reference, WG14 N2478 F.10.4.3
14064 if (!EvaluateFloat(E->getArg(0), Result, Info))
14065 return false;
14066
14067 if (Result.isNegative())
14068 Result.changeSign();
14069 return true;
14070
14071 case Builtin::BI__arithmetic_fence:
14072 return EvaluateFloat(E->getArg(0), Result, Info);
14073
14074 // FIXME: Builtin::BI__builtin_powi
14075 // FIXME: Builtin::BI__builtin_powif
14076 // FIXME: Builtin::BI__builtin_powil
14077
14078 case Builtin::BI__builtin_copysign:
14079 case Builtin::BI__builtin_copysignf:
14080 case Builtin::BI__builtin_copysignl:
14081 case Builtin::BI__builtin_copysignf128: {
14082 APFloat RHS(0.);
14083 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14084 !EvaluateFloat(E->getArg(1), RHS, Info))
14085 return false;
14086 Result.copySign(RHS);
14087 return true;
14088 }
14089
14090 case Builtin::BI__builtin_fmax:
14091 case Builtin::BI__builtin_fmaxf:
14092 case Builtin::BI__builtin_fmaxl:
14093 case Builtin::BI__builtin_fmaxf16:
14094 case Builtin::BI__builtin_fmaxf128: {
14095 // TODO: Handle sNaN.
14096 APFloat RHS(0.);
14097 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14098 !EvaluateFloat(E->getArg(1), RHS, Info))
14099 return false;
14100 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14101 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14102 Result = RHS;
14103 else if (Result.isNaN() || RHS > Result)
14104 Result = RHS;
14105 return true;
14106 }
14107
14108 case Builtin::BI__builtin_fmin:
14109 case Builtin::BI__builtin_fminf:
14110 case Builtin::BI__builtin_fminl:
14111 case Builtin::BI__builtin_fminf16:
14112 case Builtin::BI__builtin_fminf128: {
14113 // TODO: Handle sNaN.
14114 APFloat RHS(0.);
14115 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14116 !EvaluateFloat(E->getArg(1), RHS, Info))
14117 return false;
14118 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14119 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14120 Result = RHS;
14121 else if (Result.isNaN() || RHS < Result)
14122 Result = RHS;
14123 return true;
14124 }
14125 }
14126}
14127
14128bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14129 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14130 ComplexValue CV;
14131 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14132 return false;
14133 Result = CV.FloatReal;
14134 return true;
14135 }
14136
14137 return Visit(E->getSubExpr());
14138}
14139
14140bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14141 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14142 ComplexValue CV;
14143 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14144 return false;
14145 Result = CV.FloatImag;
14146 return true;
14147 }
14148
14149 VisitIgnoredValue(E->getSubExpr());
14150 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14151 Result = llvm::APFloat::getZero(Sem);
14152 return true;
14153}
14154
14155bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14156 switch (E->getOpcode()) {
14157 default: return Error(E);
14158 case UO_Plus:
14159 return EvaluateFloat(E->getSubExpr(), Result, Info);
14160 case UO_Minus:
14161 // In C standard, WG14 N2478 F.3 p4
14162 // "the unary - raises no floating point exceptions,
14163 // even if the operand is signalling."
14164 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14165 return false;
14166 Result.changeSign();
14167 return true;
14168 }
14169}
14170
14171bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14172 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14173 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14174
14175 APFloat RHS(0.0);
14176 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14177 if (!LHSOK && !Info.noteFailure())
14178 return false;
14179 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14180 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14181}
14182
14183bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14184 Result = E->getValue();
14185 return true;
14186}
14187
14188bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14189 const Expr* SubExpr = E->getSubExpr();
14190
14191 switch (E->getCastKind()) {
14192 default:
14193 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14194
14195 case CK_IntegralToFloating: {
14196 APSInt IntResult;
14197 const FPOptions FPO = E->getFPFeaturesInEffect(
14198 Info.Ctx.getLangOpts());
14199 return EvaluateInteger(SubExpr, IntResult, Info) &&
14200 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14201 IntResult, E->getType(), Result);
14202 }
14203
14204 case CK_FixedPointToFloating: {
14205 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14206 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14207 return false;
14208 Result =
14209 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14210 return true;
14211 }
14212
14213 case CK_FloatingCast: {
14214 if (!Visit(SubExpr))
14215 return false;
14216 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14217 Result);
14218 }
14219
14220 case CK_FloatingComplexToReal: {
14221 ComplexValue V;
14222 if (!EvaluateComplex(SubExpr, V, Info))
14223 return false;
14224 Result = V.getComplexFloatReal();
14225 return true;
14226 }
14227 }
14228}
14229
14230//===----------------------------------------------------------------------===//
14231// Complex Evaluation (for float and integer)
14232//===----------------------------------------------------------------------===//
14233
14234namespace {
14235class ComplexExprEvaluator
14236 : public ExprEvaluatorBase<ComplexExprEvaluator> {
14237 ComplexValue &Result;
14238
14239public:
14240 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14241 : ExprEvaluatorBaseTy(info), Result(Result) {}
14242
14243 bool Success(const APValue &V, const Expr *e) {
14244 Result.setFrom(V);
14245 return true;
14246 }
14247
14248 bool ZeroInitialization(const Expr *E);
14249
14250 //===--------------------------------------------------------------------===//
14251 // Visitor Methods
14252 //===--------------------------------------------------------------------===//
14253
14254 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14255 bool VisitCastExpr(const CastExpr *E);
14256 bool VisitBinaryOperator(const BinaryOperator *E);
14257 bool VisitUnaryOperator(const UnaryOperator *E);
14258 bool VisitInitListExpr(const InitListExpr *E);
14259 bool VisitCallExpr(const CallExpr *E);
14260};
14261} // end anonymous namespace
14262
14263static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14264 EvalInfo &Info) {
14265 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14265, __extension__ __PRETTY_FUNCTION__))
;
14266 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", 14266, __extension__ __PRETTY_FUNCTION__
))
;
14267 return ComplexExprEvaluator(Info, Result).Visit(E);
14268}
14269
14270bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14271 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14272 if (ElemTy->isRealFloatingType()) {
14273 Result.makeComplexFloat();
14274 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14275 Result.FloatReal = Zero;
14276 Result.FloatImag = Zero;
14277 } else {
14278 Result.makeComplexInt();
14279 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14280 Result.IntReal = Zero;
14281 Result.IntImag = Zero;
14282 }
14283 return true;
14284}
14285
14286bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14287 const Expr* SubExpr = E->getSubExpr();
14288
14289 if (SubExpr->getType()->isRealFloatingType()) {
14290 Result.makeComplexFloat();
14291 APFloat &Imag = Result.FloatImag;
14292 if (!EvaluateFloat(SubExpr, Imag, Info))
14293 return false;
14294
14295 Result.FloatReal = APFloat(Imag.getSemantics());
14296 return true;
14297 } else {
14298 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", 14299, __extension__ __PRETTY_FUNCTION__
))
14299 "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", 14299, __extension__ __PRETTY_FUNCTION__
))
;
14300
14301 Result.makeComplexInt();
14302 APSInt &Imag = Result.IntImag;
14303 if (!EvaluateInteger(SubExpr, Imag, Info))
14304 return false;
14305
14306 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14307 return true;
14308 }
14309}
14310
14311bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14312
14313 switch (E->getCastKind()) {
14314 case CK_BitCast:
14315 case CK_BaseToDerived:
14316 case CK_DerivedToBase:
14317 case CK_UncheckedDerivedToBase:
14318 case CK_Dynamic:
14319 case CK_ToUnion:
14320 case CK_ArrayToPointerDecay:
14321 case CK_FunctionToPointerDecay:
14322 case CK_NullToPointer:
14323 case CK_NullToMemberPointer:
14324 case CK_BaseToDerivedMemberPointer:
14325 case CK_DerivedToBaseMemberPointer:
14326 case CK_MemberPointerToBoolean:
14327 case CK_ReinterpretMemberPointer:
14328 case CK_ConstructorConversion:
14329 case CK_IntegralToPointer:
14330 case CK_PointerToIntegral:
14331 case CK_PointerToBoolean:
14332 case CK_ToVoid:
14333 case CK_VectorSplat:
14334 case CK_IntegralCast:
14335 case CK_BooleanToSignedIntegral:
14336 case CK_IntegralToBoolean:
14337 case CK_IntegralToFloating:
14338 case CK_FloatingToIntegral:
14339 case CK_FloatingToBoolean:
14340 case CK_FloatingCast:
14341 case CK_CPointerToObjCPointerCast:
14342 case CK_BlockPointerToObjCPointerCast:
14343 case CK_AnyPointerToBlockPointerCast:
14344 case CK_ObjCObjectLValueCast:
14345 case CK_FloatingComplexToReal:
14346 case CK_FloatingComplexToBoolean:
14347 case CK_IntegralComplexToReal:
14348 case CK_IntegralComplexToBoolean:
14349 case CK_ARCProduceObject:
14350 case CK_ARCConsumeObject:
14351 case CK_ARCReclaimReturnedObject:
14352 case CK_ARCExtendBlockObject:
14353 case CK_CopyAndAutoreleaseBlockObject:
14354 case CK_BuiltinFnToFnPtr:
14355 case CK_ZeroToOCLOpaqueType:
14356 case CK_NonAtomicToAtomic:
14357 case CK_AddressSpaceConversion:
14358 case CK_IntToOCLSampler:
14359 case CK_FloatingToFixedPoint:
14360 case CK_FixedPointToFloating:
14361 case CK_FixedPointCast:
14362 case CK_FixedPointToBoolean:
14363 case CK_FixedPointToIntegral:
14364 case CK_IntegralToFixedPoint:
14365 case CK_MatrixCast:
14366 llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value"
, "clang/lib/AST/ExprConstant.cpp", 14366)
;
14367
14368 case CK_LValueToRValue:
14369 case CK_AtomicToNonAtomic:
14370 case CK_NoOp:
14371 case CK_LValueToRValueBitCast:
14372 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14373
14374 case CK_Dependent:
14375 case CK_LValueBitCast:
14376 case CK_UserDefinedConversion:
14377 return Error(E);
14378
14379 case CK_FloatingRealToComplex: {
14380 APFloat &Real = Result.FloatReal;
14381 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14382 return false;
14383
14384 Result.makeComplexFloat();
14385 Result.FloatImag = APFloat(Real.getSemantics());
14386 return true;
14387 }
14388
14389 case CK_FloatingComplexCast: {
14390 if (!Visit(E->getSubExpr()))
14391 return false;
14392
14393 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14394 QualType From
14395 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14396
14397 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14398 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14399 }
14400
14401 case CK_FloatingComplexToIntegralComplex: {
14402 if (!Visit(E->getSubExpr()))
14403 return false;
14404
14405 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14406 QualType From
14407 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14408 Result.makeComplexInt();
14409 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14410 To, Result.IntReal) &&
14411 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14412 To, Result.IntImag);
14413 }
14414
14415 case CK_IntegralRealToComplex: {
14416 APSInt &Real = Result.IntReal;
14417 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14418 return false;
14419
14420 Result.makeComplexInt();
14421 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14422 return true;
14423 }
14424
14425 case CK_IntegralComplexCast: {
14426 if (!Visit(E->getSubExpr()))
14427 return false;
14428
14429 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14430 QualType From
14431 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14432
14433 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14434 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14435 return true;
14436 }
14437
14438 case CK_IntegralComplexToFloatingComplex: {
14439 if (!Visit(E->getSubExpr()))
14440 return false;
14441
14442 const FPOptions FPO = E->getFPFeaturesInEffect(
14443 Info.Ctx.getLangOpts());
14444 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14445 QualType From
14446 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14447 Result.makeComplexFloat();
14448 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14449 To, Result.FloatReal) &&
14450 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14451 To, Result.FloatImag);
14452 }
14453 }
14454
14455 llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value"
, "clang/lib/AST/ExprConstant.cpp", 14455)
;
14456}
14457
14458bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14459 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14460 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14461
14462 // Track whether the LHS or RHS is real at the type system level. When this is
14463 // the case we can simplify our evaluation strategy.
14464 bool LHSReal = false, RHSReal = false;
14465
14466 bool LHSOK;
14467 if (E->getLHS()->getType()->isRealFloatingType()) {
14468 LHSReal = true;
14469 APFloat &Real = Result.FloatReal;
14470 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14471 if (LHSOK) {
14472 Result.makeComplexFloat();
14473 Result.FloatImag = APFloat(Real.getSemantics());
14474 }
14475 } else {
14476 LHSOK = Visit(E->getLHS());
14477 }
14478 if (!LHSOK && !Info.noteFailure())
14479 return false;
14480
14481 ComplexValue RHS;
14482 if (E->getRHS()->getType()->isRealFloatingType()) {
14483 RHSReal = true;
14484 APFloat &Real = RHS.FloatReal;
14485 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14486 return false;
14487 RHS.makeComplexFloat();
14488 RHS.FloatImag = APFloat(Real.getSemantics());
14489 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14490 return false;
14491
14492 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", 14493, __extension__ __PRETTY_FUNCTION__
))
14493 "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", 14493, __extension__ __PRETTY_FUNCTION__
))
;
14494 switch (E->getOpcode()) {
14495 default: return Error(E);
14496 case BO_Add:
14497 if (Result.isComplexFloat()) {
14498 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14499 APFloat::rmNearestTiesToEven);
14500 if (LHSReal)
14501 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14502 else if (!RHSReal)
14503 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14504 APFloat::rmNearestTiesToEven);
14505 } else {
14506 Result.getComplexIntReal() += RHS.getComplexIntReal();
14507 Result.getComplexIntImag() += RHS.getComplexIntImag();
14508 }
14509 break;
14510 case BO_Sub:
14511 if (Result.isComplexFloat()) {
14512 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14513 APFloat::rmNearestTiesToEven);
14514 if (LHSReal) {
14515 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14516 Result.getComplexFloatImag().changeSign();
14517 } else if (!RHSReal) {
14518 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14519 APFloat::rmNearestTiesToEven);
14520 }
14521 } else {
14522 Result.getComplexIntReal() -= RHS.getComplexIntReal();
14523 Result.getComplexIntImag() -= RHS.getComplexIntImag();
14524 }
14525 break;
14526 case BO_Mul:
14527 if (Result.isComplexFloat()) {
14528 // This is an implementation of complex multiplication according to the
14529 // constraints laid out in C11 Annex G. The implementation uses the
14530 // following naming scheme:
14531 // (a + ib) * (c + id)
14532 ComplexValue LHS = Result;
14533 APFloat &A = LHS.getComplexFloatReal();
14534 APFloat &B = LHS.getComplexFloatImag();
14535 APFloat &C = RHS.getComplexFloatReal();
14536 APFloat &D = RHS.getComplexFloatImag();
14537 APFloat &ResR = Result.getComplexFloatReal();
14538 APFloat &ResI = Result.getComplexFloatImag();
14539 if (LHSReal) {
14540 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", 14540, __extension__ __PRETTY_FUNCTION__
))
;
14541 ResR = A * C;
14542 ResI = A * D;
14543 } else if (RHSReal) {
14544 ResR = C * A;
14545 ResI = C * B;
14546 } else {
14547 // In the fully general case, we need to handle NaNs and infinities
14548 // robustly.
14549 APFloat AC = A * C;
14550 APFloat BD = B * D;
14551 APFloat AD = A * D;
14552 APFloat BC = B * C;
14553 ResR = AC - BD;
14554 ResI = AD + BC;
14555 if (ResR.isNaN() && ResI.isNaN()) {
14556 bool Recalc = false;
14557 if (A.isInfinity() || B.isInfinity()) {
14558 A = APFloat::copySign(
14559 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14560 B = APFloat::copySign(
14561 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14562 if (C.isNaN())
14563 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14564 if (D.isNaN())
14565 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14566 Recalc = true;
14567 }
14568 if (C.isInfinity() || D.isInfinity()) {
14569 C = APFloat::copySign(
14570 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14571 D = APFloat::copySign(
14572 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14573 if (A.isNaN())
14574 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14575 if (B.isNaN())
14576 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14577 Recalc = true;
14578 }
14579 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14580 AD.isInfinity() || BC.isInfinity())) {
14581 if (A.isNaN())
14582 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14583 if (B.isNaN())
14584 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14585 if (C.isNaN())
14586 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14587 if (D.isNaN())
14588 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14589 Recalc = true;
14590 }
14591 if (Recalc) {
14592 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14593 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14594 }
14595 }
14596 }
14597 } else {
14598 ComplexValue LHS = Result;
14599 Result.getComplexIntReal() =
14600 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14601 LHS.getComplexIntImag() * RHS.getComplexIntImag());
14602 Result.getComplexIntImag() =
14603 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14604 LHS.getComplexIntImag() * RHS.getComplexIntReal());
14605 }
14606 break;
14607 case BO_Div:
14608 if (Result.isComplexFloat()) {
14609 // This is an implementation of complex division according to the
14610 // constraints laid out in C11 Annex G. The implementation uses the
14611 // following naming scheme:
14612 // (a + ib) / (c + id)
14613 ComplexValue LHS = Result;
14614 APFloat &A = LHS.getComplexFloatReal();
14615 APFloat &B = LHS.getComplexFloatImag();
14616 APFloat &C = RHS.getComplexFloatReal();
14617 APFloat &D = RHS.getComplexFloatImag();
14618 APFloat &ResR = Result.getComplexFloatReal();
14619 APFloat &ResI = Result.getComplexFloatImag();
14620 if (RHSReal) {
14621 ResR = A / C;
14622 ResI = B / C;
14623 } else {
14624 if (LHSReal) {
14625 // No real optimizations we can do here, stub out with zero.
14626 B = APFloat::getZero(A.getSemantics());
14627 }
14628 int DenomLogB = 0;
14629 APFloat MaxCD = maxnum(abs(C), abs(D));
14630 if (MaxCD.isFinite()) {
14631 DenomLogB = ilogb(MaxCD);
14632 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14633 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14634 }
14635 APFloat Denom = C * C + D * D;
14636 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14637 APFloat::rmNearestTiesToEven);
14638 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14639 APFloat::rmNearestTiesToEven);
14640 if (ResR.isNaN() && ResI.isNaN()) {
14641 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14642 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14643 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14644 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14645 D.isFinite()) {
14646 A = APFloat::copySign(
14647 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14648 B = APFloat::copySign(
14649 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14650 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14651 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14652 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14653 C = APFloat::copySign(
14654 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14655 D = APFloat::copySign(
14656 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14657 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14658 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14659 }
14660 }
14661 }
14662 } else {
14663 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14664 return Error(E, diag::note_expr_divide_by_zero);
14665
14666 ComplexValue LHS = Result;
14667 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14668 RHS.getComplexIntImag() * RHS.getComplexIntImag();
14669 Result.getComplexIntReal() =
14670 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14671 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14672 Result.getComplexIntImag() =
14673 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14674 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14675 }
14676 break;
14677 }
14678
14679 return true;
14680}
14681
14682bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14683 // Get the operand value into 'Result'.
14684 if (!Visit(E->getSubExpr()))
14685 return false;
14686
14687 switch (E->getOpcode()) {
14688 default:
14689 return Error(E);
14690 case UO_Extension:
14691 return true;
14692 case UO_Plus:
14693 // The result is always just the subexpr.
14694 return true;
14695 case UO_Minus:
14696 if (Result.isComplexFloat()) {
14697 Result.getComplexFloatReal().changeSign();
14698 Result.getComplexFloatImag().changeSign();
14699 }
14700 else {
14701 Result.getComplexIntReal() = -Result.getComplexIntReal();
14702 Result.getComplexIntImag() = -Result.getComplexIntImag();
14703 }
14704 return true;
14705 case UO_Not:
14706 if (Result.isComplexFloat())
14707 Result.getComplexFloatImag().changeSign();
14708 else
14709 Result.getComplexIntImag() = -Result.getComplexIntImag();
14710 return true;
14711 }
14712}
14713
14714bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14715 if (E->getNumInits() == 2) {
14716 if (E->getType()->isComplexType()) {
14717 Result.makeComplexFloat();
14718 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14719 return false;
14720 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14721 return false;
14722 } else {
14723 Result.makeComplexInt();
14724 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14725 return false;
14726 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14727 return false;
14728 }
14729 return true;
14730 }
14731 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14732}
14733
14734bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14735 if (!IsConstantEvaluatedBuiltinCall(E))
14736 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14737
14738 switch (E->getBuiltinCallee()) {
14739 case Builtin::BI__builtin_complex:
14740 Result.makeComplexFloat();
14741 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14742 return false;
14743 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14744 return false;
14745 return true;
14746
14747 default:
14748 return false;
14749 }
14750}
14751
14752//===----------------------------------------------------------------------===//
14753// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14754// implicit conversion.
14755//===----------------------------------------------------------------------===//
14756
14757namespace {
14758class AtomicExprEvaluator :
14759 public ExprEvaluatorBase<AtomicExprEvaluator> {
14760 const LValue *This;
14761 APValue &Result;
14762public:
14763 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14764 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14765
14766 bool Success(const APValue &V, const Expr *E) {
14767 Result = V;
14768 return true;
14769 }
14770
14771 bool ZeroInitialization(const Expr *E) {
14772 ImplicitValueInitExpr VIE(
14773 E->getType()->castAs<AtomicType>()->getValueType());
14774 // For atomic-qualified class (and array) types in C++, initialize the
14775 // _Atomic-wrapped subobject directly, in-place.
14776 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14777 : Evaluate(Result, Info, &VIE);
14778 }
14779
14780 bool VisitCastExpr(const CastExpr *E) {
14781 switch (E->getCastKind()) {
14782 default:
14783 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14784 case CK_NonAtomicToAtomic:
14785 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14786 : Evaluate(Result, Info, E->getSubExpr());
14787 }
14788 }
14789};
14790} // end anonymous namespace
14791
14792static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14793 EvalInfo &Info) {
14794 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14794, __extension__ __PRETTY_FUNCTION__))
;
14795 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", 14795, __extension__ __PRETTY_FUNCTION__
))
;
14796 return AtomicExprEvaluator(Info, This, Result).Visit(E);
14797}
14798
14799//===----------------------------------------------------------------------===//
14800// Void expression evaluation, primarily for a cast to void on the LHS of a
14801// comma operator
14802//===----------------------------------------------------------------------===//
14803
14804namespace {
14805class VoidExprEvaluator
14806 : public ExprEvaluatorBase<VoidExprEvaluator> {
14807public:
14808 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14809
14810 bool Success(const APValue &V, const Expr *e) { return true; }
14811
14812 bool ZeroInitialization(const Expr *E) { return true; }
14813
14814 bool VisitCastExpr(const CastExpr *E) {
14815 switch (E->getCastKind()) {
14816 default:
14817 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14818 case CK_ToVoid:
14819 VisitIgnoredValue(E->getSubExpr());
14820 return true;
14821 }
14822 }
14823
14824 bool VisitCallExpr(const CallExpr *E) {
14825 if (!IsConstantEvaluatedBuiltinCall(E))
14826 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14827
14828 switch (E->getBuiltinCallee()) {
14829 case Builtin::BI__assume:
14830 case Builtin::BI__builtin_assume:
14831 // The argument is not evaluated!
14832 return true;
14833
14834 case Builtin::BI__builtin_operator_delete:
14835 return HandleOperatorDeleteCall(Info, E);
14836
14837 default:
14838 return false;
14839 }
14840 }
14841
14842 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14843};
14844} // end anonymous namespace
14845
14846bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14847 // We cannot speculatively evaluate a delete expression.
14848 if (Info.SpeculativeEvaluationDepth)
14849 return false;
14850
14851 FunctionDecl *OperatorDelete = E->getOperatorDelete();
14852 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14853 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14854 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14855 return false;
14856 }
14857
14858 const Expr *Arg = E->getArgument();
14859
14860 LValue Pointer;
14861 if (!EvaluatePointer(Arg, Pointer, Info))
14862 return false;
14863 if (Pointer.Designator.Invalid)
14864 return false;
14865
14866 // Deleting a null pointer has no effect.
14867 if (Pointer.isNullPointer()) {
14868 // This is the only case where we need to produce an extension warning:
14869 // the only other way we can succeed is if we find a dynamic allocation,
14870 // and we will have warned when we allocated it in that case.
14871 if (!Info.getLangOpts().CPlusPlus20)
14872 Info.CCEDiag(E, diag::note_constexpr_new);
14873 return true;
14874 }
14875
14876 Optional<DynAlloc *> Alloc = CheckDeleteKind(
14877 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14878 if (!Alloc)
14879 return false;
14880 QualType AllocType = Pointer.Base.getDynamicAllocType();
14881
14882 // For the non-array case, the designator must be empty if the static type
14883 // does not have a virtual destructor.
14884 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14885 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14886 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14887 << Arg->getType()->getPointeeType() << AllocType;
14888 return false;
14889 }
14890
14891 // For a class type with a virtual destructor, the selected operator delete
14892 // is the one looked up when building the destructor.
14893 if (!E->isArrayForm() && !E->isGlobalDelete()) {
14894 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14895 if (VirtualDelete &&
14896 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14897 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14898 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14899 return false;
14900 }
14901 }
14902
14903 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14904 (*Alloc)->Value, AllocType))
14905 return false;
14906
14907 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14908 // The element was already erased. This means the destructor call also
14909 // deleted the object.
14910 // FIXME: This probably results in undefined behavior before we get this
14911 // far, and should be diagnosed elsewhere first.
14912 Info.FFDiag(E, diag::note_constexpr_double_delete);
14913 return false;
14914 }
14915
14916 return true;
14917}
14918
14919static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14920 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14920, __extension__ __PRETTY_FUNCTION__))
;
14921 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", 14921, __extension__ __PRETTY_FUNCTION__
))
;
14922 return VoidExprEvaluator(Info).Visit(E);
14923}
14924
14925//===----------------------------------------------------------------------===//
14926// Top level Expr::EvaluateAsRValue method.
14927//===----------------------------------------------------------------------===//
14928
14929static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14930 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 14930, __extension__ __PRETTY_FUNCTION__))
;
14931 // In C, function designators are not lvalues, but we evaluate them as if they
14932 // are.
14933 QualType T = E->getType();
14934 if (E->isGLValue() || T->isFunctionType()) {
14935 LValue LV;
14936 if (!EvaluateLValue(E, LV, Info))
14937 return false;
14938 LV.moveInto(Result);
14939 } else if (T->isVectorType()) {
14940 if (!EvaluateVector(E, Result, Info))
14941 return false;
14942 } else if (T->isIntegralOrEnumerationType()) {
14943 if (!IntExprEvaluator(Info, Result).Visit(E))
14944 return false;
14945 } else if (T->hasPointerRepresentation()) {
14946 LValue LV;
14947 if (!EvaluatePointer(E, LV, Info))
14948 return false;
14949 LV.moveInto(Result);
14950 } else if (T->isRealFloatingType()) {
14951 llvm::APFloat F(0.0);
14952 if (!EvaluateFloat(E, F, Info))
14953 return false;
14954 Result = APValue(F);
14955 } else if (T->isAnyComplexType()) {
14956 ComplexValue C;
14957 if (!EvaluateComplex(E, C, Info))
14958 return false;
14959 C.moveInto(Result);
14960 } else if (T->isFixedPointType()) {
14961 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14962 } else if (T->isMemberPointerType()) {
14963 MemberPtr P;
14964 if (!EvaluateMemberPointer(E, P, Info))
14965 return false;
14966 P.moveInto(Result);
14967 return true;
14968 } else if (T->isArrayType()) {
14969 LValue LV;
14970 APValue &Value =
14971 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14972 if (!EvaluateArray(E, LV, Value, Info))
14973 return false;
14974 Result = Value;
14975 } else if (T->isRecordType()) {
14976 LValue LV;
14977 APValue &Value =
14978 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14979 if (!EvaluateRecord(E, LV, Value, Info))
14980 return false;
14981 Result = Value;
14982 } else if (T->isVoidType()) {
14983 if (!Info.getLangOpts().CPlusPlus11)
14984 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14985 << E->getType();
14986 if (!EvaluateVoid(E, Info))
14987 return false;
14988 } else if (T->isAtomicType()) {
14989 QualType Unqual = T.getAtomicUnqualifiedType();
14990 if (Unqual->isArrayType() || Unqual->isRecordType()) {
14991 LValue LV;
14992 APValue &Value = Info.CurrentCall->createTemporary(
14993 E, Unqual, ScopeKind::FullExpression, LV);
14994 if (!EvaluateAtomic(E, &LV, Value, Info))
14995 return false;
14996 } else {
14997 if (!EvaluateAtomic(E, nullptr, Result, Info))
14998 return false;
14999 }
15000 } else if (Info.getLangOpts().CPlusPlus11) {
15001 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15002 return false;
15003 } else {
15004 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15005 return false;
15006 }
15007
15008 return true;
15009}
15010
15011/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15012/// cases, the in-place evaluation is essential, since later initializers for
15013/// an object can indirectly refer to subobjects which were initialized earlier.
15014static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15015 const Expr *E, bool AllowNonLiteralTypes) {
15016 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15016, __extension__ __PRETTY_FUNCTION__))
;
15017
15018 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15019 return false;
15020
15021 if (E->isPRValue()) {
15022 // Evaluate arrays and record types in-place, so that later initializers can
15023 // refer to earlier-initialized members of the object.
15024 QualType T = E->getType();
15025 if (T->isArrayType())
15026 return EvaluateArray(E, This, Result, Info);
15027 else if (T->isRecordType())
15028 return EvaluateRecord(E, This, Result, Info);
15029 else if (T->isAtomicType()) {
15030 QualType Unqual = T.getAtomicUnqualifiedType();
15031 if (Unqual->isArrayType() || Unqual->isRecordType())
15032 return EvaluateAtomic(E, &This, Result, Info);
15033 }
15034 }
15035
15036 // For any other type, in-place evaluation is unimportant.
15037 return Evaluate(Result, Info, E);
15038}
15039
15040/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15041/// lvalue-to-rvalue cast if it is an lvalue.
15042static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15043 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15043, __extension__ __PRETTY_FUNCTION__))
;
15044
15045 if (E->getType().isNull())
15046 return false;
15047
15048 if (!CheckLiteralType(Info, E))
15049 return false;
15050
15051 if (Info.EnableNewConstInterp) {
15052 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15053 return false;
15054 } else {
15055 if (!::Evaluate(Result, Info, E))
15056 return false;
15057 }
15058
15059 // Implicit lvalue-to-rvalue cast.
15060 if (E->isGLValue()) {
15061 LValue LV;
15062 LV.setFrom(Info.Ctx, Result);
15063 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15064 return false;
15065 }
15066
15067 // Check this core constant expression is a constant expression.
15068 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15069 ConstantExprKind::Normal) &&
15070 CheckMemoryLeaks(Info);
15071}
15072
15073static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15074 const ASTContext &Ctx, bool &IsConst) {
15075 // Fast-path evaluations of integer literals, since we sometimes see files
15076 // containing vast quantities of these.
15077 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15078 Result.Val = APValue(APSInt(L->getValue(),
15079 L->getType()->isUnsignedIntegerType()));
15080 IsConst = true;
15081 return true;
15082 }
15083
15084 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15085 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15086 IsConst = true;
15087 return true;
15088 }
15089
15090 // This case should be rare, but we need to check it before we check on
15091 // the type below.
15092 if (Exp->getType().isNull()) {
15093 IsConst = false;
15094 return true;
15095 }
15096
15097 // FIXME: Evaluating values of large array and record types can cause
15098 // performance problems. Only do so in C++11 for now.
15099 if (Exp->isPRValue() &&
15100 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15101 !Ctx.getLangOpts().CPlusPlus11) {
15102 IsConst = false;
15103 return true;
15104 }
15105 return false;
15106}
15107
15108static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15109 Expr::SideEffectsKind SEK) {
15110 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15111 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15112}
15113
15114static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15115 const ASTContext &Ctx, EvalInfo &Info) {
15116 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15116, __extension__ __PRETTY_FUNCTION__))
;
15117 bool IsConst;
15118 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15119 return IsConst;
15120
15121 return EvaluateAsRValue(Info, E, Result.Val);
15122}
15123
15124static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15125 const ASTContext &Ctx,
15126 Expr::SideEffectsKind AllowSideEffects,
15127 EvalInfo &Info) {
15128 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15128, __extension__ __PRETTY_FUNCTION__))
;
15129 if (!E->getType()->isIntegralOrEnumerationType())
15130 return false;
15131
15132 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15133 !ExprResult.Val.isInt() ||
15134 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15135 return false;
15136
15137 return true;
15138}
15139
15140static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15141 const ASTContext &Ctx,
15142 Expr::SideEffectsKind AllowSideEffects,
15143 EvalInfo &Info) {
15144 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 15144, __extension__ __PRETTY_FUNCTION__))
;
15145 if (!E->getType()->isFixedPointType())
15146 return false;
15147
15148 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15149 return false;
15150
15151 if (!ExprResult.Val.isFixedPoint() ||
15152 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15153 return false;
15154
15155 return true;
15156}
15157
15158/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15159/// any crazy technique (that has nothing to do with language standards) that
15160/// we want to. If this function returns true, it returns the folded constant
15161/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15162/// will be applied to the result.
15163bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15164 bool InConstantContext) const {
15165 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", 15166, __extension__ __PRETTY_FUNCTION__
))
15166 "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", 15166, __extension__ __PRETTY_FUNCTION__
))
;
15167 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15168 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15169 Info.InConstantContext = InConstantContext;
15170 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15171}
15172
15173bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15174 bool InConstantContext) const {
15175 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", 15176, __extension__ __PRETTY_FUNCTION__
))
15176 "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", 15176, __extension__ __PRETTY_FUNCTION__
))
;
15177 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15178 EvalResult Scratch;
15179 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15180 HandleConversionToBool(Scratch.Val, Result);
15181}
15182
15183bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15184 SideEffectsKind AllowSideEffects,
15185 bool InConstantContext) const {
15186 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", 15187, __extension__ __PRETTY_FUNCTION__
))
15187 "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", 15187, __extension__ __PRETTY_FUNCTION__
))
;
15188 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15189 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15190 Info.InConstantContext = InConstantContext;
15191 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15192}
15193
15194bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15195 SideEffectsKind AllowSideEffects,
15196 bool InConstantContext) const {
15197 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", 15198, __extension__ __PRETTY_FUNCTION__
))
15198 "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", 15198, __extension__ __PRETTY_FUNCTION__
))
;
15199 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15200 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15201 Info.InConstantContext = InConstantContext;
15202 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15203}
15204
15205bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15206 SideEffectsKind AllowSideEffects,
15207 bool InConstantContext) const {
15208 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", 15209, __extension__ __PRETTY_FUNCTION__
))
15209 "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", 15209, __extension__ __PRETTY_FUNCTION__
))
;
15210
15211 if (!getType()->isRealFloatingType())
15212 return false;
15213
15214 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15215 EvalResult ExprResult;
15216 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15217 !ExprResult.Val.isFloat() ||
15218 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15219 return false;
15220
15221 Result = ExprResult.Val.getFloat();
15222 return true;
15223}
15224
15225bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15226 bool InConstantContext) const {
15227 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", 15228, __extension__ __PRETTY_FUNCTION__
))
15228 "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", 15228, __extension__ __PRETTY_FUNCTION__
))
;
15229
15230 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15231 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15232 Info.InConstantContext = InConstantContext;
15233 LValue LV;
15234 CheckedTemporaries CheckedTemps;
15235 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15236 Result.HasSideEffects ||
15237 !CheckLValueConstantExpression(Info, getExprLoc(),
15238 Ctx.getLValueReferenceType(getType()), LV,
15239 ConstantExprKind::Normal, CheckedTemps))
15240 return false;
15241
15242 LV.moveInto(Result.Val);
15243 return true;
15244}
15245
15246static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15247 APValue DestroyedValue, QualType Type,
15248 SourceLocation Loc, Expr::EvalStatus &EStatus,
15249 bool IsConstantDestruction) {
15250 EvalInfo Info(Ctx, EStatus,
15251 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15252 : EvalInfo::EM_ConstantFold);
15253 Info.setEvaluatingDecl(Base, DestroyedValue,
15254 EvalInfo::EvaluatingDeclKind::Dtor);
15255 Info.InConstantContext = IsConstantDestruction;
15256
15257 LValue LVal;
15258 LVal.set(Base);
15259
15260 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15261 EStatus.HasSideEffects)
15262 return false;
15263
15264 if (!Info.discardCleanups())
15265 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15265)
;
15266
15267 return true;
15268}
15269
15270bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15271 ConstantExprKind Kind) const {
15272 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", 15273, __extension__ __PRETTY_FUNCTION__
))
15273 "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", 15273, __extension__ __PRETTY_FUNCTION__
))
;
15274 bool IsConst;
15275 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
15276 return true;
15277
15278 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15279 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15280 EvalInfo Info(Ctx, Result, EM);
15281 Info.InConstantContext = true;
15282
15283 // The type of the object we're initializing is 'const T' for a class NTTP.
15284 QualType T = getType();
15285 if (Kind == ConstantExprKind::ClassTemplateArgument)
15286 T.addConst();
15287
15288 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15289 // represent the result of the evaluation. CheckConstantExpression ensures
15290 // this doesn't escape.
15291 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15292 APValue::LValueBase Base(&BaseMTE);
15293
15294 Info.setEvaluatingDecl(Base, Result.Val);
15295 LValue LVal;
15296 LVal.set(Base);
15297
15298 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15299 return false;
15300
15301 if (!Info.discardCleanups())
15302 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15302)
;
15303
15304 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15305 Result.Val, Kind))
15306 return false;
15307 if (!CheckMemoryLeaks(Info))
15308 return false;
15309
15310 // If this is a class template argument, it's required to have constant
15311 // destruction too.
15312 if (Kind == ConstantExprKind::ClassTemplateArgument &&
15313 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15314 true) ||
15315 Result.HasSideEffects)) {
15316 // FIXME: Prefix a note to indicate that the problem is lack of constant
15317 // destruction.
15318 return false;
15319 }
15320
15321 return true;
15322}
15323
15324bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15325 const VarDecl *VD,
15326 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15327 bool IsConstantInitialization) const {
15328 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", 15329, __extension__ __PRETTY_FUNCTION__
))
15329 "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", 15329, __extension__ __PRETTY_FUNCTION__
))
;
15330
15331 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15332 std::string Name;
15333 llvm::raw_string_ostream OS(Name);
15334 VD->printQualifiedName(OS);
15335 return Name;
15336 });
15337
15338 // FIXME: Evaluating initializers for large array and record types can cause
15339 // performance problems. Only do so in C++11 for now.
15340 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15341 !Ctx.getLangOpts().CPlusPlus11)
15342 return false;
15343
15344 Expr::EvalStatus EStatus;
15345 EStatus.Diag = &Notes;
15346
15347 EvalInfo Info(Ctx, EStatus,
15348 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15349 ? EvalInfo::EM_ConstantExpression
15350 : EvalInfo::EM_ConstantFold);
15351 Info.setEvaluatingDecl(VD, Value);
15352 Info.InConstantContext = IsConstantInitialization;
15353
15354 SourceLocation DeclLoc = VD->getLocation();
15355 QualType DeclTy = VD->getType();
15356
15357 if (Info.EnableNewConstInterp) {
15358 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15359 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15360 return false;
15361 } else {
15362 LValue LVal;
15363 LVal.set(VD);
15364
15365 if (!EvaluateInPlace(Value, Info, LVal, this,
15366 /*AllowNonLiteralTypes=*/true) ||
15367 EStatus.HasSideEffects)
15368 return false;
15369
15370 // At this point, any lifetime-extended temporaries are completely
15371 // initialized.
15372 Info.performLifetimeExtension();
15373
15374 if (!Info.discardCleanups())
15375 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "clang/lib/AST/ExprConstant.cpp", 15375)
;
15376 }
15377 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15378 ConstantExprKind::Normal) &&
15379 CheckMemoryLeaks(Info);
15380}
15381
15382bool VarDecl::evaluateDestruction(
15383 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15384 Expr::EvalStatus EStatus;
15385 EStatus.Diag = &Notes;
15386
15387 // Only treat the destruction as constant destruction if we formally have
15388 // constant initialization (or are usable in a constant expression).
15389 bool IsConstantDestruction = hasConstantInitialization();
15390
15391 // Make a copy of the value for the destructor to mutate, if we know it.
15392 // Otherwise, treat the value as default-initialized; if the destructor works
15393 // anyway, then the destruction is constant (and must be essentially empty).
15394 APValue DestroyedValue;
15395 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15396 DestroyedValue = *getEvaluatedValue();
15397 else if (!getDefaultInitValue(getType(), DestroyedValue))
15398 return false;
15399
15400 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15401 getType(), getLocation(), EStatus,
15402 IsConstantDestruction) ||
15403 EStatus.HasSideEffects)
15404 return false;
15405
15406 ensureEvaluatedStmt()->HasConstantDestruction = true;
15407 return true;
15408}
15409
15410/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15411/// constant folded, but discard the result.
15412bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15413 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", 15414, __extension__ __PRETTY_FUNCTION__
))
15414 "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", 15414, __extension__ __PRETTY_FUNCTION__
))
;
15415
15416 EvalResult Result;
15417 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15418 !hasUnacceptableSideEffect(Result, SEK);
15419}
15420
15421APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15422 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15423 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", 15424, __extension__ __PRETTY_FUNCTION__
))
15424 "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", 15424, __extension__ __PRETTY_FUNCTION__
))
;
15425
15426 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15427 EvalResult EVResult;
15428 EVResult.Diag = Diag;
15429 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15430 Info.InConstantContext = true;
15431
15432 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15433 (void)Result;
15434 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", 15434, __extension__ __PRETTY_FUNCTION__
))
;
15435 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", 15435, __extension__ __PRETTY_FUNCTION__
))
;
15436
15437 return EVResult.Val.getInt();
15438}
15439
15440APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15441 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15442 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", 15443, __extension__ __PRETTY_FUNCTION__
))
15443 "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", 15443, __extension__ __PRETTY_FUNCTION__
))
;
15444
15445 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15446 EvalResult EVResult;
15447 EVResult.Diag = Diag;
15448 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15449 Info.InConstantContext = true;
15450 Info.CheckingForUndefinedBehavior = true;
15451
15452 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15453 (void)Result;
15454 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", 15454, __extension__ __PRETTY_FUNCTION__
))
;
15455 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", 15455, __extension__ __PRETTY_FUNCTION__
))
;
15456
15457 return EVResult.Val.getInt();
15458}
15459
15460void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15461 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", 15462, __extension__ __PRETTY_FUNCTION__
))
15462 "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", 15462, __extension__ __PRETTY_FUNCTION__
))
;
15463
15464 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15465 bool IsConst;
15466 EvalResult EVResult;
15467 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15468 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15469 Info.CheckingForUndefinedBehavior = true;
15470 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15471 }
15472}
15473
15474bool Expr::EvalResult::isGlobalLValue() const {
15475 assert(Val.isLValue())(static_cast <bool> (Val.isLValue()) ? void (0) : __assert_fail
("Val.isLValue()", "clang/lib/AST/ExprConstant.cpp", 15475, __extension__
__PRETTY_FUNCTION__))
;
15476 return IsGlobalLValue(Val.getLValueBase());
15477}
15478
15479/// isIntegerConstantExpr - this recursive routine will test if an expression is
15480/// an integer constant expression.
15481
15482/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15483/// comma, etc
15484
15485// CheckICE - This function does the fundamental ICE checking: the returned
15486// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15487// and a (possibly null) SourceLocation indicating the location of the problem.
15488//
15489// Note that to reduce code duplication, this helper does no evaluation
15490// itself; the caller checks whether the expression is evaluatable, and
15491// in the rare cases where CheckICE actually cares about the evaluated
15492// value, it calls into Evaluate.
15493
15494namespace {
15495
15496enum ICEKind {
15497 /// This expression is an ICE.
15498 IK_ICE,
15499 /// This expression is not an ICE, but if it isn't evaluated, it's
15500 /// a legal subexpression for an ICE. This return value is used to handle
15501 /// the comma operator in C99 mode, and non-constant subexpressions.
15502 IK_ICEIfUnevaluated,
15503 /// This expression is not an ICE, and is not a legal subexpression for one.
15504 IK_NotICE
15505};
15506
15507struct ICEDiag {
15508 ICEKind Kind;
15509 SourceLocation Loc;
15510
15511 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15512};
15513
15514}
15515
15516static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15517
15518static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15519
15520static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15521 Expr::EvalResult EVResult;
15522 Expr::EvalStatus Status;
15523 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15524
15525 Info.InConstantContext = true;
15526 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15527 !EVResult.Val.isInt())
15528 return ICEDiag(IK_NotICE, E->getBeginLoc());
15529
15530 return NoDiag();
15531}
15532
15533static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15534 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", 15534, __extension__ __PRETTY_FUNCTION__
))
;
15535 if (!E->getType()->isIntegralOrEnumerationType())
15536 return ICEDiag(IK_NotICE, E->getBeginLoc());
15537
15538 switch (E->getStmtClass()) {
15539#define ABSTRACT_STMT(Node)
15540#define STMT(Node, Base) case Expr::Node##Class:
15541#define EXPR(Node, Base)
15542#include "clang/AST/StmtNodes.inc"
15543 case Expr::PredefinedExprClass:
15544 case Expr::FloatingLiteralClass:
15545 case Expr::ImaginaryLiteralClass:
15546 case Expr::StringLiteralClass:
15547 case Expr::ArraySubscriptExprClass:
15548 case Expr::MatrixSubscriptExprClass:
15549 case Expr::OMPArraySectionExprClass:
15550 case Expr::OMPArrayShapingExprClass:
15551 case Expr::OMPIteratorExprClass:
15552 case Expr::MemberExprClass:
15553 case Expr::CompoundAssignOperatorClass:
15554 case Expr::CompoundLiteralExprClass:
15555 case Expr::ExtVectorElementExprClass:
15556 case Expr::DesignatedInitExprClass:
15557 case Expr::ArrayInitLoopExprClass:
15558 case Expr::ArrayInitIndexExprClass:
15559 case Expr::NoInitExprClass:
15560 case Expr::DesignatedInitUpdateExprClass:
15561 case Expr::ImplicitValueInitExprClass:
15562 case Expr::ParenListExprClass:
15563 case Expr::VAArgExprClass:
15564 case Expr::AddrLabelExprClass:
15565 case Expr::StmtExprClass:
15566 case Expr::CXXMemberCallExprClass:
15567 case Expr::CUDAKernelCallExprClass:
15568 case Expr::CXXAddrspaceCastExprClass:
15569 case Expr::CXXDynamicCastExprClass:
15570 case Expr::CXXTypeidExprClass:
15571 case Expr::CXXUuidofExprClass:
15572 case Expr::MSPropertyRefExprClass:
15573 case Expr::MSPropertySubscriptExprClass:
15574 case Expr::CXXNullPtrLiteralExprClass:
15575 case Expr::UserDefinedLiteralClass:
15576 case Expr::CXXThisExprClass:
15577 case Expr::CXXThrowExprClass:
15578 case Expr::CXXNewExprClass:
15579 case Expr::CXXDeleteExprClass:
15580 case Expr::CXXPseudoDestructorExprClass:
15581 case Expr::UnresolvedLookupExprClass:
15582 case Expr::TypoExprClass:
15583 case Expr::RecoveryExprClass:
15584 case Expr::DependentScopeDeclRefExprClass:
15585 case Expr::CXXConstructExprClass:
15586 case Expr::CXXInheritedCtorInitExprClass:
15587 case Expr::CXXStdInitializerListExprClass:
15588 case Expr::CXXBindTemporaryExprClass:
15589 case Expr::ExprWithCleanupsClass:
15590 case Expr::CXXTemporaryObjectExprClass:
15591 case Expr::CXXUnresolvedConstructExprClass:
15592 case Expr::CXXDependentScopeMemberExprClass:
15593 case Expr::UnresolvedMemberExprClass:
15594 case Expr::ObjCStringLiteralClass:
15595 case Expr::ObjCBoxedExprClass:
15596 case Expr::ObjCArrayLiteralClass:
15597 case Expr::ObjCDictionaryLiteralClass:
15598 case Expr::ObjCEncodeExprClass:
15599 case Expr::ObjCMessageExprClass:
15600 case Expr::ObjCSelectorExprClass:
15601 case Expr::ObjCProtocolExprClass:
15602 case Expr::ObjCIvarRefExprClass:
15603 case Expr::ObjCPropertyRefExprClass:
15604 case Expr::ObjCSubscriptRefExprClass:
15605 case Expr::ObjCIsaExprClass:
15606 case Expr::ObjCAvailabilityCheckExprClass:
15607 case Expr::ShuffleVectorExprClass:
15608 case Expr::ConvertVectorExprClass:
15609 case Expr::BlockExprClass:
15610 case Expr::NoStmtClass:
15611 case Expr::OpaqueValueExprClass:
15612 case Expr::PackExpansionExprClass:
15613 case Expr::SubstNonTypeTemplateParmPackExprClass:
15614 case Expr::FunctionParmPackExprClass:
15615 case Expr::AsTypeExprClass:
15616 case Expr::ObjCIndirectCopyRestoreExprClass:
15617 case Expr::MaterializeTemporaryExprClass:
15618 case Expr::PseudoObjectExprClass:
15619 case Expr::AtomicExprClass:
15620 case Expr::LambdaExprClass:
15621 case Expr::CXXFoldExprClass:
15622 case Expr::CoawaitExprClass:
15623 case Expr::DependentCoawaitExprClass:
15624 case Expr::CoyieldExprClass:
15625 case Expr::SYCLUniqueStableNameExprClass:
15626 return ICEDiag(IK_NotICE, E->getBeginLoc());
15627
15628 case Expr::InitListExprClass: {
15629 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15630 // form "T x = { a };" is equivalent to "T x = a;".
15631 // Unless we're initializing a reference, T is a scalar as it is known to be
15632 // of integral or enumeration type.
15633 if (E->isPRValue())
15634 if (cast<InitListExpr>(E)->getNumInits() == 1)
15635 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15636 return ICEDiag(IK_NotICE, E->getBeginLoc());
15637 }
15638
15639 case Expr::SizeOfPackExprClass:
15640 case Expr::GNUNullExprClass:
15641 case Expr::SourceLocExprClass:
15642 return NoDiag();
15643
15644 case Expr::SubstNonTypeTemplateParmExprClass:
15645 return
15646 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15647
15648 case Expr::ConstantExprClass:
15649 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15650
15651 case Expr::ParenExprClass:
15652 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15653 case Expr::GenericSelectionExprClass:
15654 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15655 case Expr::IntegerLiteralClass:
15656 case Expr::FixedPointLiteralClass:
15657 case Expr::CharacterLiteralClass:
15658 case Expr::ObjCBoolLiteralExprClass:
15659 case Expr::CXXBoolLiteralExprClass:
15660 case Expr::CXXScalarValueInitExprClass:
15661 case Expr::TypeTraitExprClass:
15662 case Expr::ConceptSpecializationExprClass:
15663 case Expr::RequiresExprClass:
15664 case Expr::ArrayTypeTraitExprClass:
15665 case Expr::ExpressionTraitExprClass:
15666 case Expr::CXXNoexceptExprClass:
15667 return NoDiag();
15668 case Expr::CallExprClass:
15669 case Expr::CXXOperatorCallExprClass: {
15670 // C99 6.6/3 allows function calls within unevaluated subexpressions of
15671 // constant expressions, but they can never be ICEs because an ICE cannot
15672 // contain an operand of (pointer to) function type.
15673 const CallExpr *CE = cast<CallExpr>(E);
15674 if (CE->getBuiltinCallee())
15675 return CheckEvalInICE(E, Ctx);
15676 return ICEDiag(IK_NotICE, E->getBeginLoc());
15677 }
15678 case Expr::CXXRewrittenBinaryOperatorClass:
15679 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15680 Ctx);
15681 case Expr::DeclRefExprClass: {
15682 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15683 if (isa<EnumConstantDecl>(D))
15684 return NoDiag();
15685
15686 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15687 // integer variables in constant expressions:
15688 //
15689 // C++ 7.1.5.1p2
15690 // A variable of non-volatile const-qualified integral or enumeration
15691 // type initialized by an ICE can be used in ICEs.
15692 //
15693 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15694 // that mode, use of reference variables should not be allowed.
15695 const VarDecl *VD = dyn_cast<VarDecl>(D);
15696 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15697 !VD->getType()->isReferenceType())
15698 return NoDiag();
15699
15700 return ICEDiag(IK_NotICE, E->getBeginLoc());
15701 }
15702 case Expr::UnaryOperatorClass: {
15703 const UnaryOperator *Exp = cast<UnaryOperator>(E);
15704 switch (Exp->getOpcode()) {
15705 case UO_PostInc:
15706 case UO_PostDec:
15707 case UO_PreInc:
15708 case UO_PreDec:
15709 case UO_AddrOf:
15710 case UO_Deref:
15711 case UO_Coawait:
15712 // C99 6.6/3 allows increment and decrement within unevaluated
15713 // subexpressions of constant expressions, but they can never be ICEs
15714 // because an ICE cannot contain an lvalue operand.
15715 return ICEDiag(IK_NotICE, E->getBeginLoc());
15716 case UO_Extension:
15717 case UO_LNot:
15718 case UO_Plus:
15719 case UO_Minus:
15720 case UO_Not:
15721 case UO_Real:
15722 case UO_Imag:
15723 return CheckICE(Exp->getSubExpr(), Ctx);
15724 }
15725 llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class"
, "clang/lib/AST/ExprConstant.cpp", 15725)
;
15726 }
15727 case Expr::OffsetOfExprClass: {
15728 // Note that per C99, offsetof must be an ICE. And AFAIK, using
15729 // EvaluateAsRValue matches the proposed gcc behavior for cases like
15730 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
15731 // compliance: we should warn earlier for offsetof expressions with
15732 // array subscripts that aren't ICEs, and if the array subscripts
15733 // are ICEs, the value of the offsetof must be an integer constant.
15734 return CheckEvalInICE(E, Ctx);
15735 }
15736 case Expr::UnaryExprOrTypeTraitExprClass: {
15737 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15738 if ((Exp->getKind() == UETT_SizeOf) &&
15739 Exp->getTypeOfArgument()->isVariableArrayType())
15740 return ICEDiag(IK_NotICE, E->getBeginLoc());
15741 return NoDiag();
15742 }
15743 case Expr::BinaryOperatorClass: {
15744 const BinaryOperator *Exp = cast<BinaryOperator>(E);
15745 switch (Exp->getOpcode()) {
15746 case BO_PtrMemD:
15747 case BO_PtrMemI:
15748 case BO_Assign:
15749 case BO_MulAssign:
15750 case BO_DivAssign:
15751 case BO_RemAssign:
15752 case BO_AddAssign:
15753 case BO_SubAssign:
15754 case BO_ShlAssign:
15755 case BO_ShrAssign:
15756 case BO_AndAssign:
15757 case BO_XorAssign:
15758 case BO_OrAssign:
15759 // C99 6.6/3 allows assignments within unevaluated subexpressions of
15760 // constant expressions, but they can never be ICEs because an ICE cannot
15761 // contain an lvalue operand.
15762 return ICEDiag(IK_NotICE, E->getBeginLoc());
15763
15764 case BO_Mul:
15765 case BO_Div:
15766 case BO_Rem:
15767 case BO_Add:
15768 case BO_Sub:
15769 case BO_Shl:
15770 case BO_Shr:
15771 case BO_LT:
15772 case BO_GT:
15773 case BO_LE:
15774 case BO_GE:
15775 case BO_EQ:
15776 case BO_NE:
15777 case BO_And:
15778 case BO_Xor:
15779 case BO_Or:
15780 case BO_Comma:
15781 case BO_Cmp: {
15782 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15783 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15784 if (Exp->getOpcode() == BO_Div ||
15785 Exp->getOpcode() == BO_Rem) {
15786 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15787 // we don't evaluate one.
15788 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15789 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15790 if (REval == 0)
15791 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15792 if (REval.isSigned() && REval.isAllOnes()) {
15793 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15794 if (LEval.isMinSignedValue())
15795 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15796 }
15797 }
15798 }
15799 if (Exp->getOpcode() == BO_Comma) {
15800 if (Ctx.getLangOpts().C99) {
15801 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15802 // if it isn't evaluated.
15803 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15804 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15805 } else {
15806 // In both C89 and C++, commas in ICEs are illegal.
15807 return ICEDiag(IK_NotICE, E->getBeginLoc());
15808 }
15809 }
15810 return Worst(LHSResult, RHSResult);
15811 }
15812 case BO_LAnd:
15813 case BO_LOr: {
15814 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15815 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15816 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15817 // Rare case where the RHS has a comma "side-effect"; we need
15818 // to actually check the condition to see whether the side
15819 // with the comma is evaluated.
15820 if ((Exp->getOpcode() == BO_LAnd) !=
15821 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15822 return RHSResult;
15823 return NoDiag();
15824 }
15825
15826 return Worst(LHSResult, RHSResult);
15827 }
15828 }
15829 llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind"
, "clang/lib/AST/ExprConstant.cpp", 15829)
;
15830 }
15831 case Expr::ImplicitCastExprClass:
15832 case Expr::CStyleCastExprClass:
15833 case Expr::CXXFunctionalCastExprClass:
15834 case Expr::CXXStaticCastExprClass:
15835 case Expr::CXXReinterpretCastExprClass:
15836 case Expr::CXXConstCastExprClass:
15837 case Expr::ObjCBridgedCastExprClass: {
15838 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15839 if (isa<ExplicitCastExpr>(E)) {
15840 if (const FloatingLiteral *FL
15841 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15842 unsigned DestWidth = Ctx.getIntWidth(E->getType());
15843 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15844 APSInt IgnoredVal(DestWidth, !DestSigned);
15845 bool Ignored;
15846 // If the value does not fit in the destination type, the behavior is
15847 // undefined, so we are not required to treat it as a constant
15848 // expression.
15849 if (FL->getValue().convertToInteger(IgnoredVal,
15850 llvm::APFloat::rmTowardZero,
15851 &Ignored) & APFloat::opInvalidOp)
15852 return ICEDiag(IK_NotICE, E->getBeginLoc());
15853 return NoDiag();
15854 }
15855 }
15856 switch (cast<CastExpr>(E)->getCastKind()) {
15857 case CK_LValueToRValue:
15858 case CK_AtomicToNonAtomic:
15859 case CK_NonAtomicToAtomic:
15860 case CK_NoOp:
15861 case CK_IntegralToBoolean:
15862 case CK_IntegralCast:
15863 return CheckICE(SubExpr, Ctx);
15864 default:
15865 return ICEDiag(IK_NotICE, E->getBeginLoc());
15866 }
15867 }
15868 case Expr::BinaryConditionalOperatorClass: {
15869 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15870 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15871 if (CommonResult.Kind == IK_NotICE) return CommonResult;
15872 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15873 if (FalseResult.Kind == IK_NotICE) return FalseResult;
15874 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15875 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15876 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15877 return FalseResult;
15878 }
15879 case Expr::ConditionalOperatorClass: {
15880 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15881 // If the condition (ignoring parens) is a __builtin_constant_p call,
15882 // then only the true side is actually considered in an integer constant
15883 // expression, and it is fully evaluated. This is an important GNU
15884 // extension. See GCC PR38377 for discussion.
15885 if (const CallExpr *CallCE
15886 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15887 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15888 return CheckEvalInICE(E, Ctx);
15889 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15890 if (CondResult.Kind == IK_NotICE)
15891 return CondResult;
15892
15893 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15894 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15895
15896 if (TrueResult.Kind == IK_NotICE)
15897 return TrueResult;
15898 if (FalseResult.Kind == IK_NotICE)
15899 return FalseResult;
15900 if (CondResult.Kind == IK_ICEIfUnevaluated)
15901 return CondResult;
15902 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15903 return NoDiag();
15904 // Rare case where the diagnostics depend on which side is evaluated
15905 // Note that if we get here, CondResult is 0, and at least one of
15906 // TrueResult and FalseResult is non-zero.
15907 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15908 return FalseResult;
15909 return TrueResult;
15910 }
15911 case Expr::CXXDefaultArgExprClass:
15912 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15913 case Expr::CXXDefaultInitExprClass:
15914 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15915 case Expr::ChooseExprClass: {
15916 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15917 }
15918 case Expr::BuiltinBitCastExprClass: {
15919 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15920 return ICEDiag(IK_NotICE, E->getBeginLoc());
15921 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15922 }
15923 }
15924
15925 llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "clang/lib/AST/ExprConstant.cpp"
, 15925)
;
15926}
15927
15928/// Evaluate an expression as a C++11 integral constant expression.
15929static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15930 const Expr *E,
15931 llvm::APSInt *Value,
15932 SourceLocation *Loc) {
15933 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15934 if (Loc) *Loc = E->getExprLoc();
15935 return false;
15936 }
15937
15938 APValue Result;
15939 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15940 return false;
15941
15942 if (!Result.isInt()) {
15943 if (Loc) *Loc = E->getExprLoc();
15944 return false;
15945 }
15946
15947 if (Value) *Value = Result.getInt();
15948 return true;
15949}
15950
15951bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15952 SourceLocation *Loc) const {
15953 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", 15954, __extension__ __PRETTY_FUNCTION__
))
15954 "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", 15954, __extension__ __PRETTY_FUNCTION__
))
;
15955
15956 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
15957
15958 if (Ctx.getLangOpts().CPlusPlus11)
15959 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15960
15961 ICEDiag D = CheckICE(this, Ctx);
15962 if (D.Kind != IK_ICE) {
15963 if (Loc) *Loc = D.Loc;
15964 return false;
15965 }
15966 return true;
15967}
15968
15969Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15970 SourceLocation *Loc,
15971 bool isEvaluated) const {
15972 if (isValueDependent()) {
15973 // Expression evaluator can't succeed on a dependent expression.
15974 return std::nullopt;
15975 }
15976
15977 APSInt Value;
15978
15979 if (Ctx.getLangOpts().CPlusPlus11) {
15980 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15981 return Value;
15982 return std::nullopt;
15983 }
15984
15985 if (!isIntegerConstantExpr(Ctx, Loc))
15986 return std::nullopt;
15987
15988 // The only possible side-effects here are due to UB discovered in the
15989 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15990 // required to treat the expression as an ICE, so we produce the folded
15991 // value.
15992 EvalResult ExprResult;
15993 Expr::EvalStatus Status;
15994 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15995 Info.InConstantContext = true;
15996
15997 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15998 llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!",
"clang/lib/AST/ExprConstant.cpp", 15998)
;
15999
16000 return ExprResult.Val.getInt();
16001}
16002
16003bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16004 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", 16005, __extension__ __PRETTY_FUNCTION__
))
16005 "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", 16005, __extension__ __PRETTY_FUNCTION__
))
;
16006
16007 return CheckICE(this, Ctx).Kind == IK_ICE;
16008}
16009
16010bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16011 SourceLocation *Loc) const {
16012 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", 16013, __extension__ __PRETTY_FUNCTION__
))
16013 "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", 16013, __extension__ __PRETTY_FUNCTION__
))
;
16014
16015 // We support this checking in C++98 mode in order to diagnose compatibility
16016 // issues.
16017 assert(Ctx.getLangOpts().CPlusPlus)(static_cast <bool> (Ctx.getLangOpts().CPlusPlus) ? void
(0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "clang/lib/AST/ExprConstant.cpp"
, 16017, __extension__ __PRETTY_FUNCTION__))
;
16018
16019 // Build evaluation settings.
16020 Expr::EvalStatus Status;
16021 SmallVector<PartialDiagnosticAt, 8> Diags;
16022 Status.Diag = &Diags;
16023 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16024
16025 APValue Scratch;
16026 bool IsConstExpr =
16027 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16028 // FIXME: We don't produce a diagnostic for this, but the callers that
16029 // call us on arbitrary full-expressions should generally not care.
16030 Info.discardCleanups() && !Status.HasSideEffects;
16031
16032 if (!Diags.empty()) {
16033 IsConstExpr = false;
16034 if (Loc) *Loc = Diags[0].first;
16035 } else if (!IsConstExpr) {
16036 // FIXME: This shouldn't happen.
16037 if (Loc) *Loc = getExprLoc();
16038 }
16039
16040 return IsConstExpr;
16041}
16042
16043bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16044 const FunctionDecl *Callee,
16045 ArrayRef<const Expr*> Args,
16046 const Expr *This) const {
16047 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", 16048, __extension__ __PRETTY_FUNCTION__
))
16048 "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", 16048, __extension__ __PRETTY_FUNCTION__
))
;
16049
16050 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16051 std::string Name;
16052 llvm::raw_string_ostream OS(Name);
16053 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16054 /*Qualified=*/true);
16055 return Name;
16056 });
16057
16058 Expr::EvalStatus Status;
16059 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16060 Info.InConstantContext = true;
16061
16062 LValue ThisVal;
16063 const LValue *ThisPtr = nullptr;
16064 if (This) {
16065#ifndef NDEBUG
16066 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16067 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", 16067, __extension__ __PRETTY_FUNCTION__
))
;
16068 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", 16068, __extension__ __PRETTY_FUNCTION__
))
;
16069#endif
16070 if (!This->isValueDependent() &&
16071 EvaluateObjectArgument(Info, This, ThisVal) &&
16072 !Info.EvalStatus.HasSideEffects)
16073 ThisPtr = &ThisVal;
16074
16075 // Ignore any side-effects from a failed evaluation. This is safe because
16076 // they can't interfere with any other argument evaluation.
16077 Info.EvalStatus.HasSideEffects = false;
16078 }
16079
16080 CallRef Call = Info.CurrentCall->createCall(Callee);
16081 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16082 I != E; ++I) {
16083 unsigned Idx = I - Args.begin();
16084 if (Idx >= Callee->getNumParams())
16085 break;
16086 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16087 if ((*I)->isValueDependent() ||
16088 !EvaluateCallArg(PVD, *I, Call, Info) ||
16089 Info.EvalStatus.HasSideEffects) {
16090 // If evaluation fails, throw away the argument entirely.
16091 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16092 *Slot = APValue();
16093 }
16094
16095 // Ignore any side-effects from a failed evaluation. This is safe because
16096 // they can't interfere with any other argument evaluation.
16097 Info.EvalStatus.HasSideEffects = false;
16098 }
16099
16100 // Parameter cleanups happen in the caller and are not part of this
16101 // evaluation.
16102 Info.discardCleanups();
16103 Info.EvalStatus.HasSideEffects = false;
16104
16105 // Build fake call to Callee.
16106 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16107 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16108 FullExpressionRAII Scope(Info);
16109 return Evaluate(Value, Info, this) && Scope.destroy() &&
16110 !Info.EvalStatus.HasSideEffects;
16111}
16112
16113bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16114 SmallVectorImpl<
16115 PartialDiagnosticAt> &Diags) {
16116 // FIXME: It would be useful to check constexpr function templates, but at the
16117 // moment the constant expression evaluator cannot cope with the non-rigorous
16118 // ASTs which we build for dependent expressions.
16119 if (FD->isDependentContext())
16120 return true;
16121
16122 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16123 std::string Name;
16124 llvm::raw_string_ostream OS(Name);
16125 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16126 /*Qualified=*/true);
16127 return Name;
16128 });
16129
16130 Expr::EvalStatus Status;
16131 Status.Diag = &Diags;
16132
16133 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16134 Info.InConstantContext = true;
16135 Info.CheckingPotentialConstantExpression = true;
16136
16137 // The constexpr VM attempts to compile all methods to bytecode here.
16138 if (Info.EnableNewConstInterp) {
16139 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16140 return Diags.empty();
16141 }
16142
16143 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16144 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16145
16146 // Fabricate an arbitrary expression on the stack and pretend that it
16147 // is a temporary being used as the 'this' pointer.
16148 LValue This;
16149 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16150 This.set({&VIE, Info.CurrentCall->Index});
16151
16152 ArrayRef<const Expr*> Args;
16153
16154 APValue Scratch;
16155 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16156 // Evaluate the call as a constant initializer, to allow the construction
16157 // of objects of non-literal types.
16158 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16159 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16160 } else {
16161 SourceLocation Loc = FD->getLocation();
16162 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16163 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16164 }
16165
16166 return Diags.empty();
16167}
16168
16169bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16170 const FunctionDecl *FD,
16171 SmallVectorImpl<
16172 PartialDiagnosticAt> &Diags) {
16173 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", 16174, __extension__ __PRETTY_FUNCTION__
))
16174 "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", 16174, __extension__ __PRETTY_FUNCTION__
))
;
16175
16176 Expr::EvalStatus Status;
16177 Status.Diag = &Diags;
16178
16179 EvalInfo Info(FD->getASTContext(), Status,
16180 EvalInfo::EM_ConstantExpressionUnevaluated);
16181 Info.InConstantContext = true;
16182 Info.CheckingPotentialConstantExpression = true;
16183
16184 // Fabricate a call stack frame to give the arguments a plausible cover story.
16185 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16186
16187 APValue ResultScratch;
16188 Evaluate(ResultScratch, Info, E);
16189 return Diags.empty();
16190}
16191
16192bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16193 unsigned Type) const {
16194 if (!getType()->isPointerType())
16195 return false;
16196
16197 Expr::EvalStatus Status;
16198 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16199 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16200}
16201
16202static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16203 EvalInfo &Info) {
16204 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16205 return false;
16206
16207 LValue String;
16208
16209 if (!EvaluatePointer(E, String, Info))
16210 return false;
16211
16212 QualType CharTy = E->getType()->getPointeeType();
16213
16214 // Fast path: if it's a string literal, search the string value.
16215 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16216 String.getLValueBase().dyn_cast<const Expr *>())) {
16217 StringRef Str = S->getBytes();
16218 int64_t Off = String.Offset.getQuantity();
16219 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16220 S->getCharByteWidth() == 1 &&
16221 // FIXME: Add fast-path for wchar_t too.
16222 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16223 Str = Str.substr(Off);
16224
16225 StringRef::size_type Pos = Str.find(0);
16226 if (Pos != StringRef::npos)
16227 Str = Str.substr(0, Pos);
16228
16229 Result = Str.size();
16230 return true;
16231 }
16232
16233 // Fall through to slow path.
16234 }
16235
16236 // Slow path: scan the bytes of the string looking for the terminating 0.
16237 for (uint64_t Strlen = 0; /**/; ++Strlen) {
16238 APValue Char;
16239 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16240 !Char.isInt())
16241 return false;
16242 if (!Char.getInt()) {
16243 Result = Strlen;
16244 return true;
16245 }
16246 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16247 return false;
16248 }
16249}
16250
16251bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16252 Expr::EvalStatus Status;
16253 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16254 return EvaluateBuiltinStrLen(this, Result, Info);
16255}