Bug Summary

File:tools/clang/lib/AST/ExprConstant.cpp
Warning:line 5366, column 32
Access to field 'Index' results in a dereference of a null pointer (loaded from field 'CurrentCall')

Annotated Source Code

Press '?' to see keyboard shortcuts

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