Bug Summary

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