Bug Summary

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

Annotated Source Code

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
51using namespace clang;
52using llvm::APSInt;
53using llvm::APFloat;
54
55static bool IsGlobalLValue(APValue::LValueBase B);
56
57namespace {
58 struct LValue;
59 struct CallStackFrame;
60 struct EvalInfo;
61
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 // FIXME: It's unclear where we're supposed to take the type from, and
66 // this actually matters for arrays of unknown bound. Using the type of
67 // the most recent declaration isn't clearly correct in general. Eg:
68 //
69 // extern int arr[]; void f() { extern int arr[3]; };
70 // constexpr int *p = &arr[1]; // valid?
71 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
72
73 const Expr *Base = B.get<const Expr*>();
74
75 // For a materialized temporary, the type of the temporary we materialized
76 // may not be the type of the expression.
77 if (const MaterializeTemporaryExpr *MTE =
78 dyn_cast<MaterializeTemporaryExpr>(Base)) {
79 SmallVector<const Expr *, 2> CommaLHSs;
80 SmallVector<SubobjectAdjustment, 2> Adjustments;
81 const Expr *Temp = MTE->GetTemporaryExpr();
82 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
83 Adjustments);
84 // Keep any cv-qualifiers from the reference if we generated a temporary
85 // for it directly. Otherwise use the type after adjustment.
86 if (!Adjustments.empty())
87 return Inner->getType();
88 }
89
90 return Base->getType();
91 }
92
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field or base class.
95 static
96 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
97 APValue::BaseOrMemberType Value;
98 Value.setFromOpaqueValue(E.BaseOrMember);
99 return Value;
100 }
101
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// field declaration.
104 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
105 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
106 }
107 /// Get an LValue path entry, which is known to not be an array index, as a
108 /// base class declaration.
109 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
110 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
111 }
112 /// Determine whether this LValue path entry for a base class names a virtual
113 /// base class.
114 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
115 return getAsBaseOrMember(E).getInt();
116 }
117
118 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
119 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
120 const FunctionDecl *Callee = CE->getDirectCallee();
121 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. Ignore it.
135 if (const auto *Cast = dyn_cast<CastExpr>(E))
136 E = Cast->getSubExpr()->IgnoreParens();
137
138 if (const auto *CE = dyn_cast<CallExpr>(E))
139 return getAllocSizeAttr(CE) ? CE : nullptr;
140 return nullptr;
141 }
142
143 /// Determines whether or not the given Base contains a call to a function
144 /// with the alloc_size attribute.
145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146 const auto *E = Base.dyn_cast<const Expr *>();
147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
148 }
149
150 /// The bound to claim that an array of unknown bound has.
151 /// The value in MostDerivedArraySize is undefined in this case. So, set it
152 /// to an arbitrary value that's likely to loudly break things if it's used.
153 static const uint64_t AssumedSizeForUnsizedArray =
154 std::numeric_limits<uint64_t>::max() / 2;
155
156 /// Determines if an LValue with the given LValueBase will have an unsized
157 /// array in its designator.
158 /// Find the path length and type of the most-derived subobject in the given
159 /// path, and find the size of the containing array, if any.
160 static unsigned
161 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
162 ArrayRef<APValue::LValuePathEntry> Path,
163 uint64_t &ArraySize, QualType &Type, bool &IsArray,
164 bool &FirstEntryIsUnsizedArray) {
165 // This only accepts LValueBases from APValues, and APValues don't support
166 // arrays that lack size info.
167 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 168, __extension__ __PRETTY_FUNCTION__))
168 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 168, __extension__ __PRETTY_FUNCTION__))
;
169 unsigned MostDerivedLength = 0;
170 Type = getType(Base);
171
172 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
173 if (Type->isArrayType()) {
174 const ArrayType *AT = Ctx.getAsArrayType(Type);
175 Type = AT->getElementType();
176 MostDerivedLength = I + 1;
177 IsArray = true;
178
179 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
180 ArraySize = CAT->getSize().getZExtValue();
181 } else {
182 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 182, __extension__ __PRETTY_FUNCTION__))
;
183 FirstEntryIsUnsizedArray = true;
184 ArraySize = AssumedSizeForUnsizedArray;
185 }
186 } else if (Type->isAnyComplexType()) {
187 const ComplexType *CT = Type->castAs<ComplexType>();
188 Type = CT->getElementType();
189 ArraySize = 2;
190 MostDerivedLength = I + 1;
191 IsArray = true;
192 } else if (const FieldDecl *FD = getAsField(Path[I])) {
193 Type = FD->getType();
194 ArraySize = 0;
195 MostDerivedLength = I + 1;
196 IsArray = false;
197 } else {
198 // Path[I] describes a base class.
199 ArraySize = 0;
200 IsArray = false;
201 }
202 }
203 return MostDerivedLength;
204 }
205
206 // The order of this enum is important for diagnostics.
207 enum CheckSubobjectKind {
208 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
209 CSK_This, CSK_Real, CSK_Imag
210 };
211
212 /// A path from a glvalue to a subobject of that glvalue.
213 struct SubobjectDesignator {
214 /// True if the subobject was named in a manner not supported by C++11. Such
215 /// lvalues can still be folded, but they are not core constant expressions
216 /// and we cannot perform lvalue-to-rvalue conversions on them.
217 unsigned Invalid : 1;
218
219 /// Is this a pointer one past the end of an object?
220 unsigned IsOnePastTheEnd : 1;
221
222 /// Indicator of whether the first entry is an unsized array.
223 unsigned FirstEntryIsAnUnsizedArray : 1;
224
225 /// Indicator of whether the most-derived object is an array element.
226 unsigned MostDerivedIsArrayElement : 1;
227
228 /// The length of the path to the most-derived object of which this is a
229 /// subobject.
230 unsigned MostDerivedPathLength : 28;
231
232 /// The size of the array of which the most-derived object is an element.
233 /// This will always be 0 if the most-derived object is not an array
234 /// element. 0 is not an indicator of whether or not the most-derived object
235 /// is an array, however, because 0-length arrays are allowed.
236 ///
237 /// If the current array is an unsized array, the value of this is
238 /// undefined.
239 uint64_t MostDerivedArraySize;
240
241 /// The type of the most derived object referred to by this address.
242 QualType MostDerivedType;
243
244 typedef APValue::LValuePathEntry PathEntry;
245
246 /// The entries on the path from the glvalue to the designated subobject.
247 SmallVector<PathEntry, 8> Entries;
248
249 SubobjectDesignator() : Invalid(true) {}
250
251 explicit SubobjectDesignator(QualType T)
252 : Invalid(false), IsOnePastTheEnd(false),
253 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
254 MostDerivedPathLength(0), MostDerivedArraySize(0),
255 MostDerivedType(T) {}
256
257 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
258 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
259 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
260 MostDerivedPathLength(0), MostDerivedArraySize(0) {
261 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 261, __extension__ __PRETTY_FUNCTION__))
;
262 if (!Invalid) {
263 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
264 ArrayRef<PathEntry> VEntries = V.getLValuePath();
265 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
266 if (V.getLValueBase()) {
267 bool IsArray = false;
268 bool FirstIsUnsizedArray = false;
269 MostDerivedPathLength = findMostDerivedSubobject(
270 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
271 MostDerivedType, IsArray, FirstIsUnsizedArray);
272 MostDerivedIsArrayElement = IsArray;
273 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
274 }
275 }
276 }
277
278 void setInvalid() {
279 Invalid = true;
280 Entries.clear();
281 }
282
283 /// Determine whether the most derived subobject is an array without a
284 /// known bound.
285 bool isMostDerivedAnUnsizedArray() const {
286 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
288 }
289
290 /// Determine what the most derived array's size is. Results in an assertion
291 /// failure if the most derived array lacks a size.
292 uint64_t getMostDerivedArraySize() const {
293 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 293, __extension__ __PRETTY_FUNCTION__))
;
294 return MostDerivedArraySize;
295 }
296
297 /// Determine whether this is a one-past-the-end pointer.
298 bool isOnePastTheEnd() const {
299 assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail
("!Invalid", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 if (IsOnePastTheEnd)
301 return true;
302 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
303 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
304 return true;
305 return false;
306 }
307
308 /// Check that this refers to a valid subobject.
309 bool isValidSubobject() const {
310 if (Invalid)
311 return false;
312 return !isOnePastTheEnd();
313 }
314 /// Check that this refers to a valid subobject, and if not, produce a
315 /// relevant diagnostic and set the designator as invalid.
316 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
317
318 /// Update this designator to refer to the first element within this array.
319 void addArrayUnchecked(const ConstantArrayType *CAT) {
320 PathEntry Entry;
321 Entry.ArrayIndex = 0;
322 Entries.push_back(Entry);
323
324 // This is a most-derived object.
325 MostDerivedType = CAT->getElementType();
326 MostDerivedIsArrayElement = true;
327 MostDerivedArraySize = CAT->getSize().getZExtValue();
328 MostDerivedPathLength = Entries.size();
329 }
330 /// Update this designator to refer to the first element within the array of
331 /// elements of type T. This is an array of unknown size.
332 void addUnsizedArrayUnchecked(QualType ElemTy) {
333 PathEntry Entry;
334 Entry.ArrayIndex = 0;
335 Entries.push_back(Entry);
336
337 MostDerivedType = ElemTy;
338 MostDerivedIsArrayElement = true;
339 // The value in MostDerivedArraySize is undefined in this case. So, set it
340 // to an arbitrary value that's likely to loudly break things if it's
341 // used.
342 MostDerivedArraySize = AssumedSizeForUnsizedArray;
343 MostDerivedPathLength = Entries.size();
344 }
345 /// Update this designator to refer to the given base or member of this
346 /// object.
347 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
348 PathEntry Entry;
349 APValue::BaseOrMemberType Value(D, Virtual);
350 Entry.BaseOrMember = Value.getOpaqueValue();
351 Entries.push_back(Entry);
352
353 // If this isn't a base class, it's a new most-derived object.
354 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
355 MostDerivedType = FD->getType();
356 MostDerivedIsArrayElement = false;
357 MostDerivedArraySize = 0;
358 MostDerivedPathLength = Entries.size();
359 }
360 }
361 /// Update this designator to refer to the given complex component.
362 void addComplexUnchecked(QualType EltTy, bool Imag) {
363 PathEntry Entry;
364 Entry.ArrayIndex = Imag;
365 Entries.push_back(Entry);
366
367 // This is technically a most-derived object, though in practice this
368 // is unlikely to matter.
369 MostDerivedType = EltTy;
370 MostDerivedIsArrayElement = true;
371 MostDerivedArraySize = 2;
372 MostDerivedPathLength = Entries.size();
373 }
374 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
375 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
376 const APSInt &N);
377 /// Add N to the address of this subobject.
378 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
379 if (Invalid || !N) return;
380 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
381 if (isMostDerivedAnUnsizedArray()) {
382 diagnoseUnsizedArrayPointerArithmetic(Info, E);
383 // Can't verify -- trust that the user is doing the right thing (or if
384 // not, trust that the caller will catch the bad behavior).
385 // FIXME: Should we reject if this overflows, at least?
386 Entries.back().ArrayIndex += TruncatedN;
387 return;
388 }
389
390 // [expr.add]p4: For the purposes of these operators, a pointer to a
391 // nonarray object behaves the same as a pointer to the first element of
392 // an array of length one with the type of the object as its element type.
393 bool IsArray = MostDerivedPathLength == Entries.size() &&
394 MostDerivedIsArrayElement;
395 uint64_t ArrayIndex =
396 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
397 uint64_t ArraySize =
398 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
399
400 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
401 // Calculate the actual index in a wide enough type, so we can include
402 // it in the note.
403 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
404 (llvm::APInt&)N += ArrayIndex;
405 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 405, __extension__ __PRETTY_FUNCTION__))
;
406 diagnosePointerArithmetic(Info, E, N);
407 setInvalid();
408 return;
409 }
410
411 ArrayIndex += TruncatedN;
412 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 413, __extension__ __PRETTY_FUNCTION__))
413 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 413, __extension__ __PRETTY_FUNCTION__))
;
414
415 if (IsArray)
416 Entries.back().ArrayIndex = ArrayIndex;
417 else
418 IsOnePastTheEnd = (ArrayIndex != 0);
419 }
420 };
421
422 /// A stack frame in the constexpr call stack.
423 struct CallStackFrame {
424 EvalInfo &Info;
425
426 /// Parent - The caller of this stack frame.
427 CallStackFrame *Caller;
428
429 /// Callee - The function which was called.
430 const FunctionDecl *Callee;
431
432 /// This - The binding for the this pointer in this call, if any.
433 const LValue *This;
434
435 /// Arguments - Parameter bindings for this function call, indexed by
436 /// parameters' function scope indices.
437 APValue *Arguments;
438
439 // Note that we intentionally use std::map here so that references to
440 // values are stable.
441 typedef std::map<const void*, APValue> MapTy;
442 typedef MapTy::const_iterator temp_iterator;
443 /// Temporaries - Temporary lvalues materialized within this stack frame.
444 MapTy Temporaries;
445
446 /// CallLoc - The location of the call expression for this call.
447 SourceLocation CallLoc;
448
449 /// Index - The call index of this call.
450 unsigned Index;
451
452 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
453 // on the overall stack usage of deeply-recursing constexpr evaluataions.
454 // (We should cache this map rather than recomputing it repeatedly.)
455 // But let's try this and see how it goes; we can look into caching the map
456 // as a later change.
457
458 /// LambdaCaptureFields - Mapping from captured variables/this to
459 /// corresponding data members in the closure class.
460 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
461 FieldDecl *LambdaThisCaptureField;
462
463 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
464 const FunctionDecl *Callee, const LValue *This,
465 APValue *Arguments);
466 ~CallStackFrame();
467
468 APValue *getTemporary(const void *Key) {
469 MapTy::iterator I = Temporaries.find(Key);
470 return I == Temporaries.end() ? nullptr : &I->second;
471 }
472 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
473 };
474
475 /// Temporarily override 'this'.
476 class ThisOverrideRAII {
477 public:
478 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
479 : Frame(Frame), OldThis(Frame.This) {
480 if (Enable)
481 Frame.This = NewThis;
482 }
483 ~ThisOverrideRAII() {
484 Frame.This = OldThis;
485 }
486 private:
487 CallStackFrame &Frame;
488 const LValue *OldThis;
489 };
490
491 /// A partial diagnostic which we might know in advance that we are not going
492 /// to emit.
493 class OptionalDiagnostic {
494 PartialDiagnostic *Diag;
495
496 public:
497 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
498 : Diag(Diag) {}
499
500 template<typename T>
501 OptionalDiagnostic &operator<<(const T &v) {
502 if (Diag)
503 *Diag << v;
504 return *this;
505 }
506
507 OptionalDiagnostic &operator<<(const APSInt &I) {
508 if (Diag) {
509 SmallVector<char, 32> Buffer;
510 I.toString(Buffer);
511 *Diag << StringRef(Buffer.data(), Buffer.size());
512 }
513 return *this;
514 }
515
516 OptionalDiagnostic &operator<<(const APFloat &F) {
517 if (Diag) {
518 // FIXME: Force the precision of the source value down so we don't
519 // print digits which are usually useless (we don't really care here if
520 // we truncate a digit by accident in edge cases). Ideally,
521 // APFloat::toString would automatically print the shortest
522 // representation which rounds to the correct value, but it's a bit
523 // tricky to implement.
524 unsigned precision =
525 llvm::APFloat::semanticsPrecision(F.getSemantics());
526 precision = (precision * 59 + 195) / 196;
527 SmallVector<char, 32> Buffer;
528 F.toString(Buffer, precision);
529 *Diag << StringRef(Buffer.data(), Buffer.size());
530 }
531 return *this;
532 }
533 };
534
535 /// A cleanup, and a flag indicating whether it is lifetime-extended.
536 class Cleanup {
537 llvm::PointerIntPair<APValue*, 1, bool> Value;
538
539 public:
540 Cleanup(APValue *Val, bool IsLifetimeExtended)
541 : Value(Val, IsLifetimeExtended) {}
542
543 bool isLifetimeExtended() const { return Value.getInt(); }
544 void endLifetime() {
545 *Value.getPointer() = APValue();
546 }
547 };
548
549 /// EvalInfo - This is a private struct used by the evaluator to capture
550 /// information about a subexpression as it is folded. It retains information
551 /// about the AST context, but also maintains information about the folded
552 /// expression.
553 ///
554 /// If an expression could be evaluated, it is still possible it is not a C
555 /// "integer constant expression" or constant expression. If not, this struct
556 /// captures information about how and why not.
557 ///
558 /// One bit of information passed *into* the request for constant folding
559 /// indicates whether the subexpression is "evaluated" or not according to C
560 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
561 /// evaluate the expression regardless of what the RHS is, but C only allows
562 /// certain things in certain situations.
563 struct EvalInfo {
564 ASTContext &Ctx;
565
566 /// EvalStatus - Contains information about the evaluation.
567 Expr::EvalStatus &EvalStatus;
568
569 /// CurrentCall - The top of the constexpr call stack.
570 CallStackFrame *CurrentCall;
571
572 /// CallStackDepth - The number of calls in the call stack right now.
573 unsigned CallStackDepth;
574
575 /// NextCallIndex - The next call index to assign.
576 unsigned NextCallIndex;
577
578 /// StepsLeft - The remaining number of evaluation steps we're permitted
579 /// to perform. This is essentially a limit for the number of statements
580 /// we will evaluate.
581 unsigned StepsLeft;
582
583 /// BottomFrame - The frame in which evaluation started. This must be
584 /// initialized after CurrentCall and CallStackDepth.
585 CallStackFrame BottomFrame;
586
587 /// A stack of values whose lifetimes end at the end of some surrounding
588 /// evaluation frame.
589 llvm::SmallVector<Cleanup, 16> CleanupStack;
590
591 /// EvaluatingDecl - This is the declaration whose initializer is being
592 /// evaluated, if any.
593 APValue::LValueBase EvaluatingDecl;
594
595 /// EvaluatingDeclValue - This is the value being constructed for the
596 /// declaration whose initializer is being evaluated, if any.
597 APValue *EvaluatingDeclValue;
598
599 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
600 /// the call index that that lvalue was allocated in.
601 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
602
603 /// EvaluatingConstructors - Set of objects that are currently being
604 /// constructed.
605 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
606
607 struct EvaluatingConstructorRAII {
608 EvalInfo &EI;
609 EvaluatingObject Object;
610 bool DidInsert;
611 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
612 : EI(EI), Object(Object) {
613 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
614 }
615 ~EvaluatingConstructorRAII() {
616 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
617 }
618 };
619
620 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
621 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
622 }
623
624 /// The current array initialization index, if we're performing array
625 /// initialization.
626 uint64_t ArrayInitIndex = -1;
627
628 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
629 /// notes attached to it will also be stored, otherwise they will not be.
630 bool HasActiveDiagnostic;
631
632 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
633 /// fold (not just why it's not strictly a constant expression)?
634 bool HasFoldFailureDiagnostic;
635
636 /// \brief Whether or not we're currently speculatively evaluating.
637 bool IsSpeculativelyEvaluating;
638
639 enum EvaluationMode {
640 /// Evaluate as a constant expression. Stop if we find that the expression
641 /// is not a constant expression.
642 EM_ConstantExpression,
643
644 /// Evaluate as a potential constant expression. Keep going if we hit a
645 /// construct that we can't evaluate yet (because we don't yet know the
646 /// value of something) but stop if we hit something that could never be
647 /// a constant expression.
648 EM_PotentialConstantExpression,
649
650 /// Fold the expression to a constant. Stop if we hit a side-effect that
651 /// we can't model.
652 EM_ConstantFold,
653
654 /// Evaluate the expression looking for integer overflow and similar
655 /// issues. Don't worry about side-effects, and try to visit all
656 /// subexpressions.
657 EM_EvaluateForOverflow,
658
659 /// Evaluate in any way we know how. Don't worry about side-effects that
660 /// can't be modeled.
661 EM_IgnoreSideEffects,
662
663 /// Evaluate as a constant expression. Stop if we find that the expression
664 /// is not a constant expression. Some expressions can be retried in the
665 /// optimizer if we don't constant fold them here, but in an unevaluated
666 /// context we try to fold them immediately since the optimizer never
667 /// gets a chance to look at it.
668 EM_ConstantExpressionUnevaluated,
669
670 /// Evaluate as a potential constant expression. Keep going if we hit a
671 /// construct that we can't evaluate yet (because we don't yet know the
672 /// value of something) but stop if we hit something that could never be
673 /// a constant expression. Some expressions can be retried in the
674 /// optimizer if we don't constant fold them here, but in an unevaluated
675 /// context we try to fold them immediately since the optimizer never
676 /// gets a chance to look at it.
677 EM_PotentialConstantExpressionUnevaluated,
678
679 /// Evaluate as a constant expression. In certain scenarios, if:
680 /// - we find a MemberExpr with a base that can't be evaluated, or
681 /// - we find a variable initialized with a call to a function that has
682 /// the alloc_size attribute on it
683 /// then we may consider evaluation to have succeeded.
684 ///
685 /// In either case, the LValue returned shall have an invalid base; in the
686 /// former, the base will be the invalid MemberExpr, in the latter, the
687 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
688 /// said CallExpr.
689 EM_OffsetFold,
690 } EvalMode;
691
692 /// Are we checking whether the expression is a potential constant
693 /// expression?
694 bool checkingPotentialConstantExpression() const {
695 return EvalMode == EM_PotentialConstantExpression ||
696 EvalMode == EM_PotentialConstantExpressionUnevaluated;
697 }
698
699 /// Are we checking an expression for overflow?
700 // FIXME: We should check for any kind of undefined or suspicious behavior
701 // in such constructs, not just overflow.
702 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
703
704 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
705 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
706 CallStackDepth(0), NextCallIndex(1),
707 StepsLeft(getLangOpts().ConstexprStepLimit),
708 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
709 EvaluatingDecl((const ValueDecl *)nullptr),
710 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
711 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
712 EvalMode(Mode) {}
713
714 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
715 EvaluatingDecl = Base;
716 EvaluatingDeclValue = &Value;
717 EvaluatingConstructors.insert({Base, 0});
718 }
719
720 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
721
722 bool CheckCallLimit(SourceLocation Loc) {
723 // Don't perform any constexpr calls (other than the call we're checking)
724 // when checking a potential constant expression.
725 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
726 return false;
727 if (NextCallIndex == 0) {
728 // NextCallIndex has wrapped around.
729 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
730 return false;
731 }
732 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
733 return true;
734 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
735 << getLangOpts().ConstexprCallDepth;
736 return false;
737 }
738
739 CallStackFrame *getCallFrame(unsigned CallIndex) {
740 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 740, __extension__ __PRETTY_FUNCTION__))
;
741 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
742 // be null in this loop.
743 CallStackFrame *Frame = CurrentCall;
744 while (Frame->Index > CallIndex)
745 Frame = Frame->Caller;
746 return (Frame->Index == CallIndex) ? Frame : nullptr;
747 }
748
749 bool nextStep(const Stmt *S) {
750 if (!StepsLeft) {
751 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
752 return false;
753 }
754 --StepsLeft;
755 return true;
756 }
757
758 private:
759 /// Add a diagnostic to the diagnostics list.
760 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
761 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
762 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
763 return EvalStatus.Diag->back().second;
764 }
765
766 /// Add notes containing a call stack to the current point of evaluation.
767 void addCallStack(unsigned Limit);
768
769 private:
770 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
771 unsigned ExtraNotes, bool IsCCEDiag) {
772
773 if (EvalStatus.Diag) {
774 // If we have a prior diagnostic, it will be noting that the expression
775 // isn't a constant expression. This diagnostic is more important,
776 // unless we require this evaluation to produce a constant expression.
777 //
778 // FIXME: We might want to show both diagnostics to the user in
779 // EM_ConstantFold mode.
780 if (!EvalStatus.Diag->empty()) {
781 switch (EvalMode) {
782 case EM_ConstantFold:
783 case EM_IgnoreSideEffects:
784 case EM_EvaluateForOverflow:
785 if (!HasFoldFailureDiagnostic)
786 break;
787 // We've already failed to fold something. Keep that diagnostic.
788 LLVM_FALLTHROUGH[[clang::fallthrough]];
789 case EM_ConstantExpression:
790 case EM_PotentialConstantExpression:
791 case EM_ConstantExpressionUnevaluated:
792 case EM_PotentialConstantExpressionUnevaluated:
793 case EM_OffsetFold:
794 HasActiveDiagnostic = false;
795 return OptionalDiagnostic();
796 }
797 }
798
799 unsigned CallStackNotes = CallStackDepth - 1;
800 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
801 if (Limit)
802 CallStackNotes = std::min(CallStackNotes, Limit + 1);
803 if (checkingPotentialConstantExpression())
804 CallStackNotes = 0;
805
806 HasActiveDiagnostic = true;
807 HasFoldFailureDiagnostic = !IsCCEDiag;
808 EvalStatus.Diag->clear();
809 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
810 addDiag(Loc, DiagId);
811 if (!checkingPotentialConstantExpression())
812 addCallStack(Limit);
813 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
814 }
815 HasActiveDiagnostic = false;
816 return OptionalDiagnostic();
817 }
818 public:
819 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
820 OptionalDiagnostic
821 FFDiag(SourceLocation Loc,
822 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
823 unsigned ExtraNotes = 0) {
824 return Diag(Loc, DiagId, ExtraNotes, false);
825 }
826
827 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
828 = diag::note_invalid_subexpr_in_const_expr,
829 unsigned ExtraNotes = 0) {
830 if (EvalStatus.Diag)
831 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
832 HasActiveDiagnostic = false;
833 return OptionalDiagnostic();
834 }
835
836 /// Diagnose that the evaluation does not produce a C++11 core constant
837 /// expression.
838 ///
839 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
840 /// EM_PotentialConstantExpression mode and we produce one of these.
841 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
842 = diag::note_invalid_subexpr_in_const_expr,
843 unsigned ExtraNotes = 0) {
844 // Don't override a previous diagnostic. Don't bother collecting
845 // diagnostics if we're evaluating for overflow.
846 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
847 HasActiveDiagnostic = false;
848 return OptionalDiagnostic();
849 }
850 return Diag(Loc, DiagId, ExtraNotes, true);
851 }
852 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
853 = diag::note_invalid_subexpr_in_const_expr,
854 unsigned ExtraNotes = 0) {
855 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
856 }
857 /// Add a note to a prior diagnostic.
858 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
859 if (!HasActiveDiagnostic)
860 return OptionalDiagnostic();
861 return OptionalDiagnostic(&addDiag(Loc, DiagId));
862 }
863
864 /// Add a stack of notes to a prior diagnostic.
865 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
866 if (HasActiveDiagnostic) {
867 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
868 Diags.begin(), Diags.end());
869 }
870 }
871
872 /// Should we continue evaluation after encountering a side-effect that we
873 /// couldn't model?
874 bool keepEvaluatingAfterSideEffect() {
875 switch (EvalMode) {
876 case EM_PotentialConstantExpression:
877 case EM_PotentialConstantExpressionUnevaluated:
878 case EM_EvaluateForOverflow:
879 case EM_IgnoreSideEffects:
880 return true;
881
882 case EM_ConstantExpression:
883 case EM_ConstantExpressionUnevaluated:
884 case EM_ConstantFold:
885 case EM_OffsetFold:
886 return false;
887 }
888 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 888)
;
889 }
890
891 /// Note that we have had a side-effect, and determine whether we should
892 /// keep evaluating.
893 bool noteSideEffect() {
894 EvalStatus.HasSideEffects = true;
895 return keepEvaluatingAfterSideEffect();
896 }
897
898 /// Should we continue evaluation after encountering undefined behavior?
899 bool keepEvaluatingAfterUndefinedBehavior() {
900 switch (EvalMode) {
901 case EM_EvaluateForOverflow:
902 case EM_IgnoreSideEffects:
903 case EM_ConstantFold:
904 case EM_OffsetFold:
905 return true;
906
907 case EM_PotentialConstantExpression:
908 case EM_PotentialConstantExpressionUnevaluated:
909 case EM_ConstantExpression:
910 case EM_ConstantExpressionUnevaluated:
911 return false;
912 }
913 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 913)
;
914 }
915
916 /// Note that we hit something that was technically undefined behavior, but
917 /// that we can evaluate past it (such as signed overflow or floating-point
918 /// division by zero.)
919 bool noteUndefinedBehavior() {
920 EvalStatus.HasUndefinedBehavior = true;
921 return keepEvaluatingAfterUndefinedBehavior();
922 }
923
924 /// Should we continue evaluation as much as possible after encountering a
925 /// construct which can't be reduced to a value?
926 bool keepEvaluatingAfterFailure() {
927 if (!StepsLeft)
928 return false;
929
930 switch (EvalMode) {
931 case EM_PotentialConstantExpression:
932 case EM_PotentialConstantExpressionUnevaluated:
933 case EM_EvaluateForOverflow:
934 return true;
935
936 case EM_ConstantExpression:
937 case EM_ConstantExpressionUnevaluated:
938 case EM_ConstantFold:
939 case EM_IgnoreSideEffects:
940 case EM_OffsetFold:
941 return false;
942 }
943 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 943)
;
944 }
945
946 /// Notes that we failed to evaluate an expression that other expressions
947 /// directly depend on, and determine if we should keep evaluating. This
948 /// should only be called if we actually intend to keep evaluating.
949 ///
950 /// Call noteSideEffect() instead if we may be able to ignore the value that
951 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
952 ///
953 /// (Foo(), 1) // use noteSideEffect
954 /// (Foo() || true) // use noteSideEffect
955 /// Foo() + 1 // use noteFailure
956 LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() {
957 // Failure when evaluating some expression often means there is some
958 // subexpression whose evaluation was skipped. Therefore, (because we
959 // don't track whether we skipped an expression when unwinding after an
960 // evaluation failure) every evaluation failure that bubbles up from a
961 // subexpression implies that a side-effect has potentially happened. We
962 // skip setting the HasSideEffects flag to true until we decide to
963 // continue evaluating after that point, which happens here.
964 bool KeepGoing = keepEvaluatingAfterFailure();
965 EvalStatus.HasSideEffects |= KeepGoing;
966 return KeepGoing;
967 }
968
969 class ArrayInitLoopIndex {
970 EvalInfo &Info;
971 uint64_t OuterIndex;
972
973 public:
974 ArrayInitLoopIndex(EvalInfo &Info)
975 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
976 Info.ArrayInitIndex = 0;
977 }
978 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
979
980 operator uint64_t&() { return Info.ArrayInitIndex; }
981 };
982 };
983
984 /// Object used to treat all foldable expressions as constant expressions.
985 struct FoldConstant {
986 EvalInfo &Info;
987 bool Enabled;
988 bool HadNoPriorDiags;
989 EvalInfo::EvaluationMode OldMode;
990
991 explicit FoldConstant(EvalInfo &Info, bool Enabled)
992 : Info(Info),
993 Enabled(Enabled),
994 HadNoPriorDiags(Info.EvalStatus.Diag &&
995 Info.EvalStatus.Diag->empty() &&
996 !Info.EvalStatus.HasSideEffects),
997 OldMode(Info.EvalMode) {
998 if (Enabled &&
999 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1000 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1001 Info.EvalMode = EvalInfo::EM_ConstantFold;
1002 }
1003 void keepDiagnostics() { Enabled = false; }
1004 ~FoldConstant() {
1005 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1006 !Info.EvalStatus.HasSideEffects)
1007 Info.EvalStatus.Diag->clear();
1008 Info.EvalMode = OldMode;
1009 }
1010 };
1011
1012 /// RAII object used to treat the current evaluation as the correct pointer
1013 /// offset fold for the current EvalMode
1014 struct FoldOffsetRAII {
1015 EvalInfo &Info;
1016 EvalInfo::EvaluationMode OldMode;
1017 explicit FoldOffsetRAII(EvalInfo &Info)
1018 : Info(Info), OldMode(Info.EvalMode) {
1019 if (!Info.checkingPotentialConstantExpression())
1020 Info.EvalMode = EvalInfo::EM_OffsetFold;
1021 }
1022
1023 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1024 };
1025
1026 /// RAII object used to optionally suppress diagnostics and side-effects from
1027 /// a speculative evaluation.
1028 class SpeculativeEvaluationRAII {
1029 EvalInfo *Info = nullptr;
1030 Expr::EvalStatus OldStatus;
1031 bool OldIsSpeculativelyEvaluating;
1032
1033 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1034 Info = Other.Info;
1035 OldStatus = Other.OldStatus;
1036 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1037 Other.Info = nullptr;
1038 }
1039
1040 void maybeRestoreState() {
1041 if (!Info)
1042 return;
1043
1044 Info->EvalStatus = OldStatus;
1045 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1046 }
1047
1048 public:
1049 SpeculativeEvaluationRAII() = default;
1050
1051 SpeculativeEvaluationRAII(
1052 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1053 : Info(&Info), OldStatus(Info.EvalStatus),
1054 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1055 Info.EvalStatus.Diag = NewDiag;
1056 Info.IsSpeculativelyEvaluating = true;
1057 }
1058
1059 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1060 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1061 moveFromAndCancel(std::move(Other));
1062 }
1063
1064 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1065 maybeRestoreState();
1066 moveFromAndCancel(std::move(Other));
1067 return *this;
1068 }
1069
1070 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1071 };
1072
1073 /// RAII object wrapping a full-expression or block scope, and handling
1074 /// the ending of the lifetime of temporaries created within it.
1075 template<bool IsFullExpression>
1076 class ScopeRAII {
1077 EvalInfo &Info;
1078 unsigned OldStackSize;
1079 public:
1080 ScopeRAII(EvalInfo &Info)
1081 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1082 ~ScopeRAII() {
1083 // Body moved to a static method to encourage the compiler to inline away
1084 // instances of this class.
1085 cleanup(Info, OldStackSize);
1086 }
1087 private:
1088 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1089 unsigned NewEnd = OldStackSize;
1090 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1091 I != N; ++I) {
1092 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1093 // Full-expression cleanup of a lifetime-extended temporary: nothing
1094 // to do, just move this cleanup to the right place in the stack.
1095 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1096 ++NewEnd;
1097 } else {
1098 // End the lifetime of the object.
1099 Info.CleanupStack[I].endLifetime();
1100 }
1101 }
1102 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1103 Info.CleanupStack.end());
1104 }
1105 };
1106 typedef ScopeRAII<false> BlockScopeRAII;
1107 typedef ScopeRAII<true> FullExpressionRAII;
1108}
1109
1110bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1111 CheckSubobjectKind CSK) {
1112 if (Invalid)
1113 return false;
1114 if (isOnePastTheEnd()) {
1115 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1116 << CSK;
1117 setInvalid();
1118 return false;
1119 }
1120 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1121 // must actually be at least one array element; even a VLA cannot have a
1122 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1123 return true;
1124}
1125
1126void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1127 const Expr *E) {
1128 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1129 // Do not set the designator as invalid: we can represent this situation,
1130 // and correct handling of __builtin_object_size requires us to do so.
1131}
1132
1133void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1134 const Expr *E,
1135 const APSInt &N) {
1136 // If we're complaining, we must be able to statically determine the size of
1137 // the most derived array.
1138 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1139 Info.CCEDiag(E, diag::note_constexpr_array_index)
1140 << N << /*array*/ 0
1141 << static_cast<unsigned>(getMostDerivedArraySize());
1142 else
1143 Info.CCEDiag(E, diag::note_constexpr_array_index)
1144 << N << /*non-array*/ 1;
1145 setInvalid();
1146}
1147
1148CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1149 const FunctionDecl *Callee, const LValue *This,
1150 APValue *Arguments)
1151 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1152 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1153 Info.CurrentCall = this;
1154 ++Info.CallStackDepth;
1155}
1156
1157CallStackFrame::~CallStackFrame() {
1158 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1158, __extension__ __PRETTY_FUNCTION__))
;
1159 --Info.CallStackDepth;
1160 Info.CurrentCall = Caller;
1161}
1162
1163APValue &CallStackFrame::createTemporary(const void *Key,
1164 bool IsLifetimeExtended) {
1165 APValue &Result = Temporaries[Key];
1166 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1166, __extension__ __PRETTY_FUNCTION__))
;
1167 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1168 return Result;
1169}
1170
1171static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1172
1173void EvalInfo::addCallStack(unsigned Limit) {
1174 // Determine which calls to skip, if any.
1175 unsigned ActiveCalls = CallStackDepth - 1;
1176 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1177 if (Limit && Limit < ActiveCalls) {
1178 SkipStart = Limit / 2 + Limit % 2;
1179 SkipEnd = ActiveCalls - Limit / 2;
1180 }
1181
1182 // Walk the call stack and add the diagnostics.
1183 unsigned CallIdx = 0;
1184 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1185 Frame = Frame->Caller, ++CallIdx) {
1186 // Skip this call?
1187 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1188 if (CallIdx == SkipStart) {
1189 // Note that we're skipping calls.
1190 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1191 << unsigned(ActiveCalls - Limit);
1192 }
1193 continue;
1194 }
1195
1196 // Use a different note for an inheriting constructor, because from the
1197 // user's perspective it's not really a function at all.
1198 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1199 if (CD->isInheritingConstructor()) {
1200 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1201 << CD->getParent();
1202 continue;
1203 }
1204 }
1205
1206 SmallVector<char, 128> Buffer;
1207 llvm::raw_svector_ostream Out(Buffer);
1208 describeCall(Frame, Out);
1209 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1210 }
1211}
1212
1213namespace {
1214 struct ComplexValue {
1215 private:
1216 bool IsInt;
1217
1218 public:
1219 APSInt IntReal, IntImag;
1220 APFloat FloatReal, FloatImag;
1221
1222 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1223
1224 void makeComplexFloat() { IsInt = false; }
1225 bool isComplexFloat() const { return !IsInt; }
1226 APFloat &getComplexFloatReal() { return FloatReal; }
1227 APFloat &getComplexFloatImag() { return FloatImag; }
1228
1229 void makeComplexInt() { IsInt = true; }
1230 bool isComplexInt() const { return IsInt; }
1231 APSInt &getComplexIntReal() { return IntReal; }
1232 APSInt &getComplexIntImag() { return IntImag; }
1233
1234 void moveInto(APValue &v) const {
1235 if (isComplexFloat())
1236 v = APValue(FloatReal, FloatImag);
1237 else
1238 v = APValue(IntReal, IntImag);
1239 }
1240 void setFrom(const APValue &v) {
1241 assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt
()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1241, __extension__ __PRETTY_FUNCTION__))
;
1242 if (v.isComplexFloat()) {
1243 makeComplexFloat();
1244 FloatReal = v.getComplexFloatReal();
1245 FloatImag = v.getComplexFloatImag();
1246 } else {
1247 makeComplexInt();
1248 IntReal = v.getComplexIntReal();
1249 IntImag = v.getComplexIntImag();
1250 }
1251 }
1252 };
1253
1254 struct LValue {
1255 APValue::LValueBase Base;
1256 CharUnits Offset;
1257 unsigned InvalidBase : 1;
1258 unsigned CallIndex : 31;
1259 SubobjectDesignator Designator;
1260 bool IsNullPtr;
1261
1262 const APValue::LValueBase getLValueBase() const { return Base; }
1263 CharUnits &getLValueOffset() { return Offset; }
1264 const CharUnits &getLValueOffset() const { return Offset; }
1265 unsigned getLValueCallIndex() const { return CallIndex; }
1266 SubobjectDesignator &getLValueDesignator() { return Designator; }
1267 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1268 bool isNullPointer() const { return IsNullPtr;}
1269
1270 void moveInto(APValue &V) const {
1271 if (Designator.Invalid)
1272 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1273 IsNullPtr);
1274 else {
1275 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1275, __extension__ __PRETTY_FUNCTION__))
;
1276 V = APValue(Base, Offset, Designator.Entries,
1277 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1278 }
1279 }
1280 void setFrom(ASTContext &Ctx, const APValue &V) {
1281 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1281, __extension__ __PRETTY_FUNCTION__))
;
1282 Base = V.getLValueBase();
1283 Offset = V.getLValueOffset();
1284 InvalidBase = false;
1285 CallIndex = V.getLValueCallIndex();
1286 Designator = SubobjectDesignator(Ctx, V);
1287 IsNullPtr = V.isNullPointer();
1288 }
1289
1290 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1291#ifndef NDEBUG
1292 // We only allow a few types of invalid bases. Enforce that here.
1293 if (BInvalid) {
1294 const auto *E = B.get<const Expr *>();
1295 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1296, __extension__ __PRETTY_FUNCTION__))
1296 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1296, __extension__ __PRETTY_FUNCTION__))
;
1297 }
1298#endif
1299
1300 Base = B;
1301 Offset = CharUnits::fromQuantity(0);
1302 InvalidBase = BInvalid;
1303 CallIndex = I;
1304 Designator = SubobjectDesignator(getType(B));
1305 IsNullPtr = false;
1306 }
1307
1308 void setNull(QualType PointerTy, uint64_t TargetVal) {
1309 Base = (Expr *)nullptr;
1310 Offset = CharUnits::fromQuantity(TargetVal);
1311 InvalidBase = false;
1312 CallIndex = 0;
1313 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1314 IsNullPtr = true;
1315 }
1316
1317 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1318 set(B, I, true);
1319 }
1320
1321 // Check that this LValue is not based on a null pointer. If it is, produce
1322 // a diagnostic and mark the designator as invalid.
1323 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1324 CheckSubobjectKind CSK) {
1325 if (Designator.Invalid)
1326 return false;
1327 if (IsNullPtr) {
1328 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1329 << CSK;
1330 Designator.setInvalid();
1331 return false;
1332 }
1333 return true;
1334 }
1335
1336 // Check this LValue refers to an object. If not, set the designator to be
1337 // invalid and emit a diagnostic.
1338 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1339 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1340 Designator.checkSubobject(Info, E, CSK);
1341 }
1342
1343 void addDecl(EvalInfo &Info, const Expr *E,
1344 const Decl *D, bool Virtual = false) {
1345 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1346 Designator.addDeclUnchecked(D, Virtual);
1347 }
1348 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1349 if (!Designator.Entries.empty()) {
1350 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1351 Designator.setInvalid();
1352 return;
1353 }
1354 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1355 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1355, __extension__ __PRETTY_FUNCTION__))
;
1356 Designator.FirstEntryIsAnUnsizedArray = true;
1357 Designator.addUnsizedArrayUnchecked(ElemTy);
1358 }
1359 }
1360 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1361 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1362 Designator.addArrayUnchecked(CAT);
1363 }
1364 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1365 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1366 Designator.addComplexUnchecked(EltTy, Imag);
1367 }
1368 void clearIsNullPointer() {
1369 IsNullPtr = false;
1370 }
1371 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1372 const APSInt &Index, CharUnits ElementSize) {
1373 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1374 // but we're not required to diagnose it and it's valid in C++.)
1375 if (!Index)
1376 return;
1377
1378 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1379 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1380 // offsets.
1381 uint64_t Offset64 = Offset.getQuantity();
1382 uint64_t ElemSize64 = ElementSize.getQuantity();
1383 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1384 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1385
1386 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1387 Designator.adjustIndex(Info, E, Index);
1388 clearIsNullPointer();
1389 }
1390 void adjustOffset(CharUnits N) {
1391 Offset += N;
1392 if (N.getQuantity())
1393 clearIsNullPointer();
1394 }
1395 };
1396
1397 struct MemberPtr {
1398 MemberPtr() {}
1399 explicit MemberPtr(const ValueDecl *Decl) :
1400 DeclAndIsDerivedMember(Decl, false), Path() {}
1401
1402 /// The member or (direct or indirect) field referred to by this member
1403 /// pointer, or 0 if this is a null member pointer.
1404 const ValueDecl *getDecl() const {
1405 return DeclAndIsDerivedMember.getPointer();
1406 }
1407 /// Is this actually a member of some type derived from the relevant class?
1408 bool isDerivedMember() const {
1409 return DeclAndIsDerivedMember.getInt();
1410 }
1411 /// Get the class which the declaration actually lives in.
1412 const CXXRecordDecl *getContainingRecord() const {
1413 return cast<CXXRecordDecl>(
1414 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1415 }
1416
1417 void moveInto(APValue &V) const {
1418 V = APValue(getDecl(), isDerivedMember(), Path);
1419 }
1420 void setFrom(const APValue &V) {
1421 assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail
("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1421, __extension__ __PRETTY_FUNCTION__))
;
1422 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1423 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1424 Path.clear();
1425 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1426 Path.insert(Path.end(), P.begin(), P.end());
1427 }
1428
1429 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1430 /// whether the member is a member of some class derived from the class type
1431 /// of the member pointer.
1432 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1433 /// Path - The path of base/derived classes from the member declaration's
1434 /// class (exclusive) to the class type of the member pointer (inclusive).
1435 SmallVector<const CXXRecordDecl*, 4> Path;
1436
1437 /// Perform a cast towards the class of the Decl (either up or down the
1438 /// hierarchy).
1439 bool castBack(const CXXRecordDecl *Class) {
1440 assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail
("!Path.empty()", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1440, __extension__ __PRETTY_FUNCTION__))
;
1441 const CXXRecordDecl *Expected;
1442 if (Path.size() >= 2)
1443 Expected = Path[Path.size() - 2];
1444 else
1445 Expected = getContainingRecord();
1446 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1447 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1448 // if B does not contain the original member and is not a base or
1449 // derived class of the class containing the original member, the result
1450 // of the cast is undefined.
1451 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1452 // (D::*). We consider that to be a language defect.
1453 return false;
1454 }
1455 Path.pop_back();
1456 return true;
1457 }
1458 /// Perform a base-to-derived member pointer cast.
1459 bool castToDerived(const CXXRecordDecl *Derived) {
1460 if (!getDecl())
1461 return true;
1462 if (!isDerivedMember()) {
1463 Path.push_back(Derived);
1464 return true;
1465 }
1466 if (!castBack(Derived))
1467 return false;
1468 if (Path.empty())
1469 DeclAndIsDerivedMember.setInt(false);
1470 return true;
1471 }
1472 /// Perform a derived-to-base member pointer cast.
1473 bool castToBase(const CXXRecordDecl *Base) {
1474 if (!getDecl())
1475 return true;
1476 if (Path.empty())
1477 DeclAndIsDerivedMember.setInt(true);
1478 if (isDerivedMember()) {
1479 Path.push_back(Base);
1480 return true;
1481 }
1482 return castBack(Base);
1483 }
1484 };
1485
1486 /// Compare two member pointers, which are assumed to be of the same type.
1487 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1488 if (!LHS.getDecl() || !RHS.getDecl())
1489 return !LHS.getDecl() && !RHS.getDecl();
1490 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1491 return false;
1492 return LHS.Path == RHS.Path;
1493 }
1494}
1495
1496static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1497static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1498 const LValue &This, const Expr *E,
1499 bool AllowNonLiteralTypes = false);
1500static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1501 bool InvalidBaseOK = false);
1502static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1503 bool InvalidBaseOK = false);
1504static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1505 EvalInfo &Info);
1506static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1507static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1508static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1509 EvalInfo &Info);
1510static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1511static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1512static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1513 EvalInfo &Info);
1514static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1515
1516//===----------------------------------------------------------------------===//
1517// Misc utilities
1518//===----------------------------------------------------------------------===//
1519
1520/// Negate an APSInt in place, converting it to a signed form if necessary, and
1521/// preserving its value (by extending by up to one bit as needed).
1522static void negateAsSigned(APSInt &Int) {
1523 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1524 Int = Int.extend(Int.getBitWidth() + 1);
1525 Int.setIsSigned(true);
1526 }
1527 Int = -Int;
1528}
1529
1530/// Produce a string describing the given constexpr call.
1531static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1532 unsigned ArgIndex = 0;
1533 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1534 !isa<CXXConstructorDecl>(Frame->Callee) &&
1535 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1536
1537 if (!IsMemberCall)
1538 Out << *Frame->Callee << '(';
1539
1540 if (Frame->This && IsMemberCall) {
1541 APValue Val;
1542 Frame->This->moveInto(Val);
1543 Val.printPretty(Out, Frame->Info.Ctx,
1544 Frame->This->Designator.MostDerivedType);
1545 // FIXME: Add parens around Val if needed.
1546 Out << "->" << *Frame->Callee << '(';
1547 IsMemberCall = false;
1548 }
1549
1550 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1551 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1552 if (ArgIndex > (unsigned)IsMemberCall)
1553 Out << ", ";
1554
1555 const ParmVarDecl *Param = *I;
1556 const APValue &Arg = Frame->Arguments[ArgIndex];
1557 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1558
1559 if (ArgIndex == 0 && IsMemberCall)
1560 Out << "->" << *Frame->Callee << '(';
1561 }
1562
1563 Out << ')';
1564}
1565
1566/// Evaluate an expression to see if it had side-effects, and discard its
1567/// result.
1568/// \return \c true if the caller should keep evaluating.
1569static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1570 APValue Scratch;
1571 if (!Evaluate(Scratch, Info, E))
1572 // We don't need the value, but we might have skipped a side effect here.
1573 return Info.noteSideEffect();
1574 return true;
1575}
1576
1577/// Should this call expression be treated as a string literal?
1578static bool IsStringLiteralCall(const CallExpr *E) {
1579 unsigned Builtin = E->getBuiltinCallee();
1580 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1581 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1582}
1583
1584static bool IsGlobalLValue(APValue::LValueBase B) {
1585 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1586 // constant expression of pointer type that evaluates to...
1587
1588 // ... a null pointer value, or a prvalue core constant expression of type
1589 // std::nullptr_t.
1590 if (!B) return true;
1591
1592 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1593 // ... the address of an object with static storage duration,
1594 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1595 return VD->hasGlobalStorage();
1596 // ... the address of a function,
1597 return isa<FunctionDecl>(D);
1598 }
1599
1600 const Expr *E = B.get<const Expr*>();
1601 switch (E->getStmtClass()) {
1602 default:
1603 return false;
1604 case Expr::CompoundLiteralExprClass: {
1605 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1606 return CLE->isFileScope() && CLE->isLValue();
1607 }
1608 case Expr::MaterializeTemporaryExprClass:
1609 // A materialized temporary might have been lifetime-extended to static
1610 // storage duration.
1611 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1612 // A string literal has static storage duration.
1613 case Expr::StringLiteralClass:
1614 case Expr::PredefinedExprClass:
1615 case Expr::ObjCStringLiteralClass:
1616 case Expr::ObjCEncodeExprClass:
1617 case Expr::CXXTypeidExprClass:
1618 case Expr::CXXUuidofExprClass:
1619 return true;
1620 case Expr::CallExprClass:
1621 return IsStringLiteralCall(cast<CallExpr>(E));
1622 // For GCC compatibility, &&label has static storage duration.
1623 case Expr::AddrLabelExprClass:
1624 return true;
1625 // A Block literal expression may be used as the initialization value for
1626 // Block variables at global or local static scope.
1627 case Expr::BlockExprClass:
1628 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1629 case Expr::ImplicitValueInitExprClass:
1630 // FIXME:
1631 // We can never form an lvalue with an implicit value initialization as its
1632 // base through expression evaluation, so these only appear in one case: the
1633 // implicit variable declaration we invent when checking whether a constexpr
1634 // constructor can produce a constant expression. We must assume that such
1635 // an expression might be a global lvalue.
1636 return true;
1637 }
1638}
1639
1640static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1641 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
;
1642 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1643 if (VD)
1644 Info.Note(VD->getLocation(), diag::note_declared_at);
1645 else
1646 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1647 diag::note_constexpr_temporary_here);
1648}
1649
1650/// Check that this reference or pointer core constant expression is a valid
1651/// value for an address or reference constant expression. Return true if we
1652/// can fold this expression, whether or not it's a constant expression.
1653static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1654 QualType Type, const LValue &LVal) {
1655 bool IsReferenceType = Type->isReferenceType();
1656
1657 APValue::LValueBase Base = LVal.getLValueBase();
1658 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1659
1660 // Check that the object is a global. Note that the fake 'this' object we
1661 // manufacture when checking potential constant expressions is conservatively
1662 // assumed to be global here.
1663 if (!IsGlobalLValue(Base)) {
1664 if (Info.getLangOpts().CPlusPlus11) {
1665 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1666 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1667 << IsReferenceType << !Designator.Entries.empty()
1668 << !!VD << VD;
1669 NoteLValueLocation(Info, Base);
1670 } else {
1671 Info.FFDiag(Loc);
1672 }
1673 // Don't allow references to temporaries to escape.
1674 return false;
1675 }
1676 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1678, __extension__ __PRETTY_FUNCTION__))
1677 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1678, __extension__ __PRETTY_FUNCTION__))
1678 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1678, __extension__ __PRETTY_FUNCTION__))
;
1679
1680 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1681 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1682 // Check if this is a thread-local variable.
1683 if (Var->getTLSKind())
1684 return false;
1685
1686 // A dllimport variable never acts like a constant.
1687 if (Var->hasAttr<DLLImportAttr>())
1688 return false;
1689 }
1690 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1691 // __declspec(dllimport) must be handled very carefully:
1692 // We must never initialize an expression with the thunk in C++.
1693 // Doing otherwise would allow the same id-expression to yield
1694 // different addresses for the same function in different translation
1695 // units. However, this means that we must dynamically initialize the
1696 // expression with the contents of the import address table at runtime.
1697 //
1698 // The C language has no notion of ODR; furthermore, it has no notion of
1699 // dynamic initialization. This means that we are permitted to
1700 // perform initialization with the address of the thunk.
1701 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1702 return false;
1703 }
1704 }
1705
1706 // Allow address constant expressions to be past-the-end pointers. This is
1707 // an extension: the standard requires them to point to an object.
1708 if (!IsReferenceType)
1709 return true;
1710
1711 // A reference constant expression must refer to an object.
1712 if (!Base) {
1713 // FIXME: diagnostic
1714 Info.CCEDiag(Loc);
1715 return true;
1716 }
1717
1718 // Does this refer one past the end of some object?
1719 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1720 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1721 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1722 << !Designator.Entries.empty() << !!VD << VD;
1723 NoteLValueLocation(Info, Base);
1724 }
1725
1726 return true;
1727}
1728
1729/// Member pointers are constant expressions unless they point to a
1730/// non-virtual dllimport member function.
1731static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1732 SourceLocation Loc,
1733 QualType Type,
1734 const APValue &Value) {
1735 const ValueDecl *Member = Value.getMemberPointerDecl();
1736 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1737 if (!FD)
1738 return true;
1739 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1740}
1741
1742/// Check that this core constant expression is of literal type, and if not,
1743/// produce an appropriate diagnostic.
1744static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1745 const LValue *This = nullptr) {
1746 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1747 return true;
1748
1749 // C++1y: A constant initializer for an object o [...] may also invoke
1750 // constexpr constructors for o and its subobjects even if those objects
1751 // are of non-literal class types.
1752 //
1753 // C++11 missed this detail for aggregates, so classes like this:
1754 // struct foo_t { union { int i; volatile int j; } u; };
1755 // are not (obviously) initializable like so:
1756 // __attribute__((__require_constant_initialization__))
1757 // static const foo_t x = {{0}};
1758 // because "i" is a subobject with non-literal initialization (due to the
1759 // volatile member of the union). See:
1760 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1761 // Therefore, we use the C++1y behavior.
1762 if (This && Info.EvaluatingDecl == This->getLValueBase())
1763 return true;
1764
1765 // Prvalue constant expressions must be of literal types.
1766 if (Info.getLangOpts().CPlusPlus11)
1767 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1768 << E->getType();
1769 else
1770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1771 return false;
1772}
1773
1774/// Check that this core constant expression value is a valid value for a
1775/// constant expression. If not, report an appropriate diagnostic. Does not
1776/// check that the expression is of literal type.
1777static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1778 QualType Type, const APValue &Value) {
1779 if (Value.isUninit()) {
1780 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1781 << true << Type;
1782 return false;
1783 }
1784
1785 // We allow _Atomic(T) to be initialized from anything that T can be
1786 // initialized from.
1787 if (const AtomicType *AT = Type->getAs<AtomicType>())
1788 Type = AT->getValueType();
1789
1790 // Core issue 1454: For a literal constant expression of array or class type,
1791 // each subobject of its value shall have been initialized by a constant
1792 // expression.
1793 if (Value.isArray()) {
1794 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1795 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1796 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1797 Value.getArrayInitializedElt(I)))
1798 return false;
1799 }
1800 if (!Value.hasArrayFiller())
1801 return true;
1802 return CheckConstantExpression(Info, DiagLoc, EltTy,
1803 Value.getArrayFiller());
1804 }
1805 if (Value.isUnion() && Value.getUnionField()) {
1806 return CheckConstantExpression(Info, DiagLoc,
1807 Value.getUnionField()->getType(),
1808 Value.getUnionValue());
1809 }
1810 if (Value.isStruct()) {
1811 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1812 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1813 unsigned BaseIndex = 0;
1814 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1815 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1816 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1817 Value.getStructBase(BaseIndex)))
1818 return false;
1819 }
1820 }
1821 for (const auto *I : RD->fields()) {
1822 if (I->isUnnamedBitfield())
1823 continue;
1824
1825 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1826 Value.getStructField(I->getFieldIndex())))
1827 return false;
1828 }
1829 }
1830
1831 if (Value.isLValue()) {
1832 LValue LVal;
1833 LVal.setFrom(Info.Ctx, Value);
1834 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1835 }
1836
1837 if (Value.isMemberPointer())
1838 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1839
1840 // Everything else is fine.
1841 return true;
1842}
1843
1844static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1845 return LVal.Base.dyn_cast<const ValueDecl*>();
1846}
1847
1848static bool IsLiteralLValue(const LValue &Value) {
1849 if (Value.CallIndex)
1850 return false;
1851 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1852 return E && !isa<MaterializeTemporaryExpr>(E);
1853}
1854
1855static bool IsWeakLValue(const LValue &Value) {
1856 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1857 return Decl && Decl->isWeak();
1858}
1859
1860static bool isZeroSized(const LValue &Value) {
1861 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1862 if (Decl && isa<VarDecl>(Decl)) {
1863 QualType Ty = Decl->getType();
1864 if (Ty->isArrayType())
1865 return Ty->isIncompleteType() ||
1866 Decl->getASTContext().getTypeSize(Ty) == 0;
1867 }
1868 return false;
1869}
1870
1871static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1872 // A null base expression indicates a null pointer. These are always
1873 // evaluatable, and they are false unless the offset is zero.
1874 if (!Value.getLValueBase()) {
1875 Result = !Value.getLValueOffset().isZero();
1876 return true;
1877 }
1878
1879 // We have a non-null base. These are generally known to be true, but if it's
1880 // a weak declaration it can be null at runtime.
1881 Result = true;
1882 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1883 return !Decl || !Decl->isWeak();
1884}
1885
1886static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1887 switch (Val.getKind()) {
1888 case APValue::Uninitialized:
1889 return false;
1890 case APValue::Int:
1891 Result = Val.getInt().getBoolValue();
1892 return true;
1893 case APValue::Float:
1894 Result = !Val.getFloat().isZero();
1895 return true;
1896 case APValue::ComplexInt:
1897 Result = Val.getComplexIntReal().getBoolValue() ||
1898 Val.getComplexIntImag().getBoolValue();
1899 return true;
1900 case APValue::ComplexFloat:
1901 Result = !Val.getComplexFloatReal().isZero() ||
1902 !Val.getComplexFloatImag().isZero();
1903 return true;
1904 case APValue::LValue:
1905 return EvalPointerValueAsBool(Val, Result);
1906 case APValue::MemberPointer:
1907 Result = Val.getMemberPointerDecl();
1908 return true;
1909 case APValue::Vector:
1910 case APValue::Array:
1911 case APValue::Struct:
1912 case APValue::Union:
1913 case APValue::AddrLabelDiff:
1914 return false;
1915 }
1916
1917 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1917)
;
1918}
1919
1920static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1921 EvalInfo &Info) {
1922 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1922, __extension__ __PRETTY_FUNCTION__))
;
1923 APValue Val;
1924 if (!Evaluate(Val, Info, E))
1925 return false;
1926 return HandleConversionToBool(Val, Result);
1927}
1928
1929template<typename T>
1930static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1931 const T &SrcValue, QualType DestType) {
1932 Info.CCEDiag(E, diag::note_constexpr_overflow)
1933 << SrcValue << DestType;
1934 return Info.noteUndefinedBehavior();
1935}
1936
1937static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1938 QualType SrcType, const APFloat &Value,
1939 QualType DestType, APSInt &Result) {
1940 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1941 // Determine whether we are converting to unsigned or signed.
1942 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1943
1944 Result = APSInt(DestWidth, !DestSigned);
1945 bool ignored;
1946 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1947 & APFloat::opInvalidOp)
1948 return HandleOverflow(Info, E, Value, DestType);
1949 return true;
1950}
1951
1952static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1953 QualType SrcType, QualType DestType,
1954 APFloat &Result) {
1955 APFloat Value = Result;
1956 bool ignored;
1957 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1958 APFloat::rmNearestTiesToEven, &ignored)
1959 & APFloat::opOverflow)
1960 return HandleOverflow(Info, E, Value, DestType);
1961 return true;
1962}
1963
1964static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1965 QualType DestType, QualType SrcType,
1966 const APSInt &Value) {
1967 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1968 APSInt Result = Value;
1969 // Figure out if this is a truncate, extend or noop cast.
1970 // If the input is signed, do a sign extend, noop, or truncate.
1971 Result = Result.extOrTrunc(DestWidth);
1972 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1973 return Result;
1974}
1975
1976static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1977 QualType SrcType, const APSInt &Value,
1978 QualType DestType, APFloat &Result) {
1979 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1980 if (Result.convertFromAPInt(Value, Value.isSigned(),
1981 APFloat::rmNearestTiesToEven)
1982 & APFloat::opOverflow)
1983 return HandleOverflow(Info, E, Value, DestType);
1984 return true;
1985}
1986
1987static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1988 APValue &Value, const FieldDecl *FD) {
1989 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1989, __extension__ __PRETTY_FUNCTION__))
;
1990
1991 if (!Value.isInt()) {
1992 // Trying to store a pointer-cast-to-integer into a bitfield.
1993 // FIXME: In this case, we should provide the diagnostic for casting
1994 // a pointer to an integer.
1995 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 1995, __extension__ __PRETTY_FUNCTION__))
;
1996 Info.FFDiag(E);
1997 return false;
1998 }
1999
2000 APSInt &Int = Value.getInt();
2001 unsigned OldBitWidth = Int.getBitWidth();
2002 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2003 if (NewBitWidth < OldBitWidth)
2004 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2005 return true;
2006}
2007
2008static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2009 llvm::APInt &Res) {
2010 APValue SVal;
2011 if (!Evaluate(SVal, Info, E))
2012 return false;
2013 if (SVal.isInt()) {
2014 Res = SVal.getInt();
2015 return true;
2016 }
2017 if (SVal.isFloat()) {
2018 Res = SVal.getFloat().bitcastToAPInt();
2019 return true;
2020 }
2021 if (SVal.isVector()) {
2022 QualType VecTy = E->getType();
2023 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2024 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2025 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2026 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2027 Res = llvm::APInt::getNullValue(VecSize);
2028 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2029 APValue &Elt = SVal.getVectorElt(i);
2030 llvm::APInt EltAsInt;
2031 if (Elt.isInt()) {
2032 EltAsInt = Elt.getInt();
2033 } else if (Elt.isFloat()) {
2034 EltAsInt = Elt.getFloat().bitcastToAPInt();
2035 } else {
2036 // Don't try to handle vectors of anything other than int or float
2037 // (not sure if it's possible to hit this case).
2038 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2039 return false;
2040 }
2041 unsigned BaseEltSize = EltAsInt.getBitWidth();
2042 if (BigEndian)
2043 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2044 else
2045 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2046 }
2047 return true;
2048 }
2049 // Give up if the input isn't an int, float, or vector. For example, we
2050 // reject "(v4i16)(intptr_t)&a".
2051 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2052 return false;
2053}
2054
2055/// Perform the given integer operation, which is known to need at most BitWidth
2056/// bits, and check for overflow in the original type (if that type was not an
2057/// unsigned type).
2058template<typename Operation>
2059static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2060 const APSInt &LHS, const APSInt &RHS,
2061 unsigned BitWidth, Operation Op,
2062 APSInt &Result) {
2063 if (LHS.isUnsigned()) {
2064 Result = Op(LHS, RHS);
2065 return true;
2066 }
2067
2068 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2069 Result = Value.trunc(LHS.getBitWidth());
2070 if (Result.extend(BitWidth) != Value) {
2071 if (Info.checkingForOverflow())
2072 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2073 diag::warn_integer_constant_overflow)
2074 << Result.toString(10) << E->getType();
2075 else
2076 return HandleOverflow(Info, E, Value, E->getType());
2077 }
2078 return true;
2079}
2080
2081/// Perform the given binary integer operation.
2082static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2083 BinaryOperatorKind Opcode, APSInt RHS,
2084 APSInt &Result) {
2085 switch (Opcode) {
2086 default:
2087 Info.FFDiag(E);
2088 return false;
2089 case BO_Mul:
2090 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2091 std::multiplies<APSInt>(), Result);
2092 case BO_Add:
2093 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2094 std::plus<APSInt>(), Result);
2095 case BO_Sub:
2096 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2097 std::minus<APSInt>(), Result);
2098 case BO_And: Result = LHS & RHS; return true;
2099 case BO_Xor: Result = LHS ^ RHS; return true;
2100 case BO_Or: Result = LHS | RHS; return true;
2101 case BO_Div:
2102 case BO_Rem:
2103 if (RHS == 0) {
2104 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2105 return false;
2106 }
2107 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2108 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2109 // this operation and gives the two's complement result.
2110 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2111 LHS.isSigned() && LHS.isMinSignedValue())
2112 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2113 E->getType());
2114 return true;
2115 case BO_Shl: {
2116 if (Info.getLangOpts().OpenCL)
2117 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2118 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2119 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2120 RHS.isUnsigned());
2121 else if (RHS.isSigned() && RHS.isNegative()) {
2122 // During constant-folding, a negative shift is an opposite shift. Such
2123 // a shift is not a constant expression.
2124 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2125 RHS = -RHS;
2126 goto shift_right;
2127 }
2128 shift_left:
2129 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2130 // the shifted type.
2131 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2132 if (SA != RHS) {
2133 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2134 << RHS << E->getType() << LHS.getBitWidth();
2135 } else if (LHS.isSigned()) {
2136 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2137 // operand, and must not overflow the corresponding unsigned type.
2138 if (LHS.isNegative())
2139 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2140 else if (LHS.countLeadingZeros() < SA)
2141 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2142 }
2143 Result = LHS << SA;
2144 return true;
2145 }
2146 case BO_Shr: {
2147 if (Info.getLangOpts().OpenCL)
2148 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2149 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2150 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2151 RHS.isUnsigned());
2152 else if (RHS.isSigned() && RHS.isNegative()) {
2153 // During constant-folding, a negative shift is an opposite shift. Such a
2154 // shift is not a constant expression.
2155 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2156 RHS = -RHS;
2157 goto shift_left;
2158 }
2159 shift_right:
2160 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2161 // shifted type.
2162 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2163 if (SA != RHS)
2164 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2165 << RHS << E->getType() << LHS.getBitWidth();
2166 Result = LHS >> SA;
2167 return true;
2168 }
2169
2170 case BO_LT: Result = LHS < RHS; return true;
2171 case BO_GT: Result = LHS > RHS; return true;
2172 case BO_LE: Result = LHS <= RHS; return true;
2173 case BO_GE: Result = LHS >= RHS; return true;
2174 case BO_EQ: Result = LHS == RHS; return true;
2175 case BO_NE: Result = LHS != RHS; return true;
2176 }
2177}
2178
2179/// Perform the given binary floating-point operation, in-place, on LHS.
2180static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2181 APFloat &LHS, BinaryOperatorKind Opcode,
2182 const APFloat &RHS) {
2183 switch (Opcode) {
2184 default:
2185 Info.FFDiag(E);
2186 return false;
2187 case BO_Mul:
2188 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2189 break;
2190 case BO_Add:
2191 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2192 break;
2193 case BO_Sub:
2194 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2195 break;
2196 case BO_Div:
2197 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2198 break;
2199 }
2200
2201 if (LHS.isInfinity() || LHS.isNaN()) {
2202 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2203 return Info.noteUndefinedBehavior();
2204 }
2205 return true;
2206}
2207
2208/// Cast an lvalue referring to a base subobject to a derived class, by
2209/// truncating the lvalue's path to the given length.
2210static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2211 const RecordDecl *TruncatedType,
2212 unsigned TruncatedElements) {
2213 SubobjectDesignator &D = Result.Designator;
2214
2215 // Check we actually point to a derived class object.
2216 if (TruncatedElements == D.Entries.size())
2217 return true;
2218 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2219, __extension__ __PRETTY_FUNCTION__))
2219 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2219, __extension__ __PRETTY_FUNCTION__))
;
2220 if (!Result.checkSubobject(Info, E, CSK_Derived))
2221 return false;
2222
2223 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2224 const RecordDecl *RD = TruncatedType;
2225 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2226 if (RD->isInvalidDecl()) return false;
2227 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2228 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2229 if (isVirtualBaseClass(D.Entries[I]))
2230 Result.Offset -= Layout.getVBaseClassOffset(Base);
2231 else
2232 Result.Offset -= Layout.getBaseClassOffset(Base);
2233 RD = Base;
2234 }
2235 D.Entries.resize(TruncatedElements);
2236 return true;
2237}
2238
2239static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2240 const CXXRecordDecl *Derived,
2241 const CXXRecordDecl *Base,
2242 const ASTRecordLayout *RL = nullptr) {
2243 if (!RL) {
2244 if (Derived->isInvalidDecl()) return false;
2245 RL = &Info.Ctx.getASTRecordLayout(Derived);
2246 }
2247
2248 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2249 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2250 return true;
2251}
2252
2253static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2254 const CXXRecordDecl *DerivedDecl,
2255 const CXXBaseSpecifier *Base) {
2256 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2257
2258 if (!Base->isVirtual())
2259 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2260
2261 SubobjectDesignator &D = Obj.Designator;
2262 if (D.Invalid)
2263 return false;
2264
2265 // Extract most-derived object and corresponding type.
2266 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2267 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2268 return false;
2269
2270 // Find the virtual base class.
2271 if (DerivedDecl->isInvalidDecl()) return false;
2272 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2273 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2274 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2275 return true;
2276}
2277
2278static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2279 QualType Type, LValue &Result) {
2280 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2281 PathE = E->path_end();
2282 PathI != PathE; ++PathI) {
2283 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2284 *PathI))
2285 return false;
2286 Type = (*PathI)->getType();
2287 }
2288 return true;
2289}
2290
2291/// Update LVal to refer to the given field, which must be a member of the type
2292/// currently described by LVal.
2293static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2294 const FieldDecl *FD,
2295 const ASTRecordLayout *RL = nullptr) {
2296 if (!RL) {
2297 if (FD->getParent()->isInvalidDecl()) return false;
2298 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2299 }
2300
2301 unsigned I = FD->getFieldIndex();
2302 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2303 LVal.addDecl(Info, E, FD);
2304 return true;
2305}
2306
2307/// Update LVal to refer to the given indirect field.
2308static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2309 LValue &LVal,
2310 const IndirectFieldDecl *IFD) {
2311 for (const auto *C : IFD->chain())
2312 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2313 return false;
2314 return true;
2315}
2316
2317/// Get the size of the given type in char units.
2318static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2319 QualType Type, CharUnits &Size) {
2320 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2321 // extension.
2322 if (Type->isVoidType() || Type->isFunctionType()) {
2323 Size = CharUnits::One();
2324 return true;
2325 }
2326
2327 if (Type->isDependentType()) {
2328 Info.FFDiag(Loc);
2329 return false;
2330 }
2331
2332 if (!Type->isConstantSizeType()) {
2333 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2334 // FIXME: Better diagnostic.
2335 Info.FFDiag(Loc);
2336 return false;
2337 }
2338
2339 Size = Info.Ctx.getTypeSizeInChars(Type);
2340 return true;
2341}
2342
2343/// Update a pointer value to model pointer arithmetic.
2344/// \param Info - Information about the ongoing evaluation.
2345/// \param E - The expression being evaluated, for diagnostic purposes.
2346/// \param LVal - The pointer value to be updated.
2347/// \param EltTy - The pointee type represented by LVal.
2348/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2349static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2350 LValue &LVal, QualType EltTy,
2351 APSInt Adjustment) {
2352 CharUnits SizeOfPointee;
2353 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
19
Called C++ object pointer is null
2354 return false;
2355
2356 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2357 return true;
2358}
2359
2360static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2361 LValue &LVal, QualType EltTy,
2362 int64_t Adjustment) {
2363 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
17
Passing null pointer value via 2nd parameter 'E'
18
Calling 'HandleLValueArrayAdjustment'
2364 APSInt::get(Adjustment));
2365}
2366
2367/// Update an lvalue to refer to a component of a complex number.
2368/// \param Info - Information about the ongoing evaluation.
2369/// \param LVal - The lvalue to be updated.
2370/// \param EltTy - The complex number's component type.
2371/// \param Imag - False for the real component, true for the imaginary.
2372static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2373 LValue &LVal, QualType EltTy,
2374 bool Imag) {
2375 if (Imag) {
2376 CharUnits SizeOfComponent;
2377 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2378 return false;
2379 LVal.Offset += SizeOfComponent;
2380 }
2381 LVal.addComplex(Info, E, EltTy, Imag);
2382 return true;
2383}
2384
2385static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2386 QualType Type, const LValue &LVal,
2387 APValue &RVal);
2388
2389/// Try to evaluate the initializer for a variable declaration.
2390///
2391/// \param Info Information about the ongoing evaluation.
2392/// \param E An expression to be used when printing diagnostics.
2393/// \param VD The variable whose initializer should be obtained.
2394/// \param Frame The frame in which the variable was created. Must be null
2395/// if this variable is not local to the evaluation.
2396/// \param Result Filled in with a pointer to the value of the variable.
2397static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2398 const VarDecl *VD, CallStackFrame *Frame,
2399 APValue *&Result) {
2400
2401 // If this is a parameter to an active constexpr function call, perform
2402 // argument substitution.
2403 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2404 // Assume arguments of a potential constant expression are unknown
2405 // constant expressions.
2406 if (Info.checkingPotentialConstantExpression())
2407 return false;
2408 if (!Frame || !Frame->Arguments) {
2409 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2410 return false;
2411 }
2412 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2413 return true;
2414 }
2415
2416 // If this is a local variable, dig out its value.
2417 if (Frame) {
2418 Result = Frame->getTemporary(VD);
2419 if (!Result) {
2420 // Assume variables referenced within a lambda's call operator that were
2421 // not declared within the call operator are captures and during checking
2422 // of a potential constant expression, assume they are unknown constant
2423 // expressions.
2424 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2426, __extension__ __PRETTY_FUNCTION__))
2425 (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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2426, __extension__ __PRETTY_FUNCTION__))
2426 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2426, __extension__ __PRETTY_FUNCTION__))
;
2427 if (Info.checkingPotentialConstantExpression())
2428 return false;
2429 // FIXME: implement capture evaluation during constant expr evaluation.
2430 Info.FFDiag(E->getLocStart(),
2431 diag::note_unimplemented_constexpr_lambda_feature_ast)
2432 << "captures not currently allowed";
2433 return false;
2434 }
2435 return true;
2436 }
2437
2438 // Dig out the initializer, and use the declaration which it's attached to.
2439 const Expr *Init = VD->getAnyInitializer(VD);
2440 if (!Init || Init->isValueDependent()) {
2441 // If we're checking a potential constant expression, the variable could be
2442 // initialized later.
2443 if (!Info.checkingPotentialConstantExpression())
2444 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2445 return false;
2446 }
2447
2448 // If we're currently evaluating the initializer of this declaration, use that
2449 // in-flight value.
2450 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2451 Result = Info.EvaluatingDeclValue;
2452 return true;
2453 }
2454
2455 // Never evaluate the initializer of a weak variable. We can't be sure that
2456 // this is the definition which will be used.
2457 if (VD->isWeak()) {
2458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2459 return false;
2460 }
2461
2462 // Check that we can fold the initializer. In C++, we will have already done
2463 // this in the cases where it matters for conformance.
2464 SmallVector<PartialDiagnosticAt, 8> Notes;
2465 if (!VD->evaluateValue(Notes)) {
2466 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2467 Notes.size() + 1) << VD;
2468 Info.Note(VD->getLocation(), diag::note_declared_at);
2469 Info.addNotes(Notes);
2470 return false;
2471 } else if (!VD->checkInitIsICE()) {
2472 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2473 Notes.size() + 1) << VD;
2474 Info.Note(VD->getLocation(), diag::note_declared_at);
2475 Info.addNotes(Notes);
2476 }
2477
2478 Result = VD->getEvaluatedValue();
2479 return true;
2480}
2481
2482static bool IsConstNonVolatile(QualType T) {
2483 Qualifiers Quals = T.getQualifiers();
2484 return Quals.hasConst() && !Quals.hasVolatile();
2485}
2486
2487/// Get the base index of the given base class within an APValue representing
2488/// the given derived class.
2489static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2490 const CXXRecordDecl *Base) {
2491 Base = Base->getCanonicalDecl();
2492 unsigned Index = 0;
2493 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2494 E = Derived->bases_end(); I != E; ++I, ++Index) {
2495 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2496 return Index;
2497 }
2498
2499 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2499)
;
2500}
2501
2502/// Extract the value of a character from a string literal.
2503static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2504 uint64_t Index) {
2505 // FIXME: Support MakeStringConstant
2506 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2507 std::string Str;
2508 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2509 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2509, __extension__ __PRETTY_FUNCTION__))
;
2510 return APSInt::getUnsigned(Str.c_str()[Index]);
2511 }
2512
2513 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2514 Lit = PE->getFunctionName();
2515 const StringLiteral *S = cast<StringLiteral>(Lit);
2516 const ConstantArrayType *CAT =
2517 Info.Ctx.getAsConstantArrayType(S->getType());
2518 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2518, __extension__ __PRETTY_FUNCTION__))
;
2519 QualType CharType = CAT->getElementType();
2520 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2520, __extension__ __PRETTY_FUNCTION__))
;
2521
2522 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2523 CharType->isUnsignedIntegerType());
2524 if (Index < S->getLength())
2525 Value = S->getCodeUnit(Index);
2526 return Value;
2527}
2528
2529// Expand a string literal into an array of characters.
2530static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2531 APValue &Result) {
2532 const StringLiteral *S = cast<StringLiteral>(Lit);
2533 const ConstantArrayType *CAT =
2534 Info.Ctx.getAsConstantArrayType(S->getType());
2535 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2535, __extension__ __PRETTY_FUNCTION__))
;
2536 QualType CharType = CAT->getElementType();
2537 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2537, __extension__ __PRETTY_FUNCTION__))
;
2538
2539 unsigned Elts = CAT->getSize().getZExtValue();
2540 Result = APValue(APValue::UninitArray(),
2541 std::min(S->getLength(), Elts), Elts);
2542 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2543 CharType->isUnsignedIntegerType());
2544 if (Result.hasArrayFiller())
2545 Result.getArrayFiller() = APValue(Value);
2546 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2547 Value = S->getCodeUnit(I);
2548 Result.getArrayInitializedElt(I) = APValue(Value);
2549 }
2550}
2551
2552// Expand an array so that it has more than Index filled elements.
2553static void expandArray(APValue &Array, unsigned Index) {
2554 unsigned Size = Array.getArraySize();
2555 assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail
("Index < Size", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2555, __extension__ __PRETTY_FUNCTION__))
;
2556
2557 // Always at least double the number of elements for which we store a value.
2558 unsigned OldElts = Array.getArrayInitializedElts();
2559 unsigned NewElts = std::max(Index+1, OldElts * 2);
2560 NewElts = std::min(Size, std::max(NewElts, 8u));
2561
2562 // Copy the data across.
2563 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2564 for (unsigned I = 0; I != OldElts; ++I)
2565 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2566 for (unsigned I = OldElts; I != NewElts; ++I)
2567 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2568 if (NewValue.hasArrayFiller())
2569 NewValue.getArrayFiller() = Array.getArrayFiller();
2570 Array.swap(NewValue);
2571}
2572
2573/// Determine whether a type would actually be read by an lvalue-to-rvalue
2574/// conversion. If it's of class type, we may assume that the copy operation
2575/// is trivial. Note that this is never true for a union type with fields
2576/// (because the copy always "reads" the active member) and always true for
2577/// a non-class type.
2578static bool isReadByLvalueToRvalueConversion(QualType T) {
2579 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2580 if (!RD || (RD->isUnion() && !RD->field_empty()))
2581 return true;
2582 if (RD->isEmpty())
2583 return false;
2584
2585 for (auto *Field : RD->fields())
2586 if (isReadByLvalueToRvalueConversion(Field->getType()))
2587 return true;
2588
2589 for (auto &BaseSpec : RD->bases())
2590 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2591 return true;
2592
2593 return false;
2594}
2595
2596/// Diagnose an attempt to read from any unreadable field within the specified
2597/// type, which might be a class type.
2598static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2599 QualType T) {
2600 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2601 if (!RD)
2602 return false;
2603
2604 if (!RD->hasMutableFields())
2605 return false;
2606
2607 for (auto *Field : RD->fields()) {
2608 // If we're actually going to read this field in some way, then it can't
2609 // be mutable. If we're in a union, then assigning to a mutable field
2610 // (even an empty one) can change the active member, so that's not OK.
2611 // FIXME: Add core issue number for the union case.
2612 if (Field->isMutable() &&
2613 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2614 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2615 Info.Note(Field->getLocation(), diag::note_declared_at);
2616 return true;
2617 }
2618
2619 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2620 return true;
2621 }
2622
2623 for (auto &BaseSpec : RD->bases())
2624 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2625 return true;
2626
2627 // All mutable fields were empty, and thus not actually read.
2628 return false;
2629}
2630
2631/// Kinds of access we can perform on an object, for diagnostics.
2632enum AccessKinds {
2633 AK_Read,
2634 AK_Assign,
2635 AK_Increment,
2636 AK_Decrement
2637};
2638
2639namespace {
2640/// A handle to a complete object (an object that is not a subobject of
2641/// another object).
2642struct CompleteObject {
2643 /// The value of the complete object.
2644 APValue *Value;
2645 /// The type of the complete object.
2646 QualType Type;
2647
2648 CompleteObject() : Value(nullptr) {}
2649 CompleteObject(APValue *Value, QualType Type)
2650 : Value(Value), Type(Type) {
2651 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2651, __extension__ __PRETTY_FUNCTION__))
;
2652 }
2653
2654 explicit operator bool() const { return Value; }
2655};
2656} // end anonymous namespace
2657
2658/// Find the designated sub-object of an rvalue.
2659template<typename SubobjectHandler>
2660typename SubobjectHandler::result_type
2661findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2662 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2663 if (Sub.Invalid)
2664 // A diagnostic will have already been produced.
2665 return handler.failed();
2666 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2667 if (Info.getLangOpts().CPlusPlus11)
2668 Info.FFDiag(E, Sub.isOnePastTheEnd()
2669 ? diag::note_constexpr_access_past_end
2670 : diag::note_constexpr_access_unsized_array)
2671 << handler.AccessKind;
2672 else
2673 Info.FFDiag(E);
2674 return handler.failed();
2675 }
2676
2677 APValue *O = Obj.Value;
2678 QualType ObjType = Obj.Type;
2679 const FieldDecl *LastField = nullptr;
2680
2681 // Walk the designator's path to find the subobject.
2682 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2683 if (O->isUninit()) {
2684 if (!Info.checkingPotentialConstantExpression())
2685 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2686 return handler.failed();
2687 }
2688
2689 if (I == N) {
2690 // If we are reading an object of class type, there may still be more
2691 // things we need to check: if there are any mutable subobjects, we
2692 // cannot perform this read. (This only happens when performing a trivial
2693 // copy or assignment.)
2694 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2695 diagnoseUnreadableFields(Info, E, ObjType))
2696 return handler.failed();
2697
2698 if (!handler.found(*O, ObjType))
2699 return false;
2700
2701 // If we modified a bit-field, truncate it to the right width.
2702 if (handler.AccessKind != AK_Read &&
2703 LastField && LastField->isBitField() &&
2704 !truncateBitfieldValue(Info, E, *O, LastField))
2705 return false;
2706
2707 return true;
2708 }
2709
2710 LastField = nullptr;
2711 if (ObjType->isArrayType()) {
2712 // Next subobject is an array element.
2713 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2714 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715 uint64_t Index = Sub.Entries[I].ArrayIndex;
2716 if (CAT->getSize().ule(Index)) {
2717 // Note, it should not be possible to form a pointer with a valid
2718 // designator which points more than one past the end of the array.
2719 if (Info.getLangOpts().CPlusPlus11)
2720 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2721 << handler.AccessKind;
2722 else
2723 Info.FFDiag(E);
2724 return handler.failed();
2725 }
2726
2727 ObjType = CAT->getElementType();
2728
2729 // An array object is represented as either an Array APValue or as an
2730 // LValue which refers to a string literal.
2731 if (O->isLValue()) {
2732 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2732, __extension__ __PRETTY_FUNCTION__))
;
2733 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2733, __extension__ __PRETTY_FUNCTION__))
;
2734 if (handler.AccessKind != AK_Read)
2735 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2736 *O);
2737 else
2738 return handler.foundString(*O, ObjType, Index);
2739 }
2740
2741 if (O->getArrayInitializedElts() > Index)
2742 O = &O->getArrayInitializedElt(Index);
2743 else if (handler.AccessKind != AK_Read) {
2744 expandArray(*O, Index);
2745 O = &O->getArrayInitializedElt(Index);
2746 } else
2747 O = &O->getArrayFiller();
2748 } else if (ObjType->isAnyComplexType()) {
2749 // Next subobject is a complex number.
2750 uint64_t Index = Sub.Entries[I].ArrayIndex;
2751 if (Index > 1) {
2752 if (Info.getLangOpts().CPlusPlus11)
2753 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2754 << handler.AccessKind;
2755 else
2756 Info.FFDiag(E);
2757 return handler.failed();
2758 }
2759
2760 bool WasConstQualified = ObjType.isConstQualified();
2761 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2762 if (WasConstQualified)
2763 ObjType.addConst();
2764
2765 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2765, __extension__ __PRETTY_FUNCTION__))
;
2766 if (O->isComplexInt()) {
2767 return handler.found(Index ? O->getComplexIntImag()
2768 : O->getComplexIntReal(), ObjType);
2769 } else {
2770 assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0)
: __assert_fail ("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2770, __extension__ __PRETTY_FUNCTION__))
;
2771 return handler.found(Index ? O->getComplexFloatImag()
2772 : O->getComplexFloatReal(), ObjType);
2773 }
2774 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2775 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2776 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2777 << Field;
2778 Info.Note(Field->getLocation(), diag::note_declared_at);
2779 return handler.failed();
2780 }
2781
2782 // Next subobject is a class, struct or union field.
2783 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2784 if (RD->isUnion()) {
2785 const FieldDecl *UnionField = O->getUnionField();
2786 if (!UnionField ||
2787 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2788 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2789 << handler.AccessKind << Field << !UnionField << UnionField;
2790 return handler.failed();
2791 }
2792 O = &O->getUnionValue();
2793 } else
2794 O = &O->getStructField(Field->getFieldIndex());
2795
2796 bool WasConstQualified = ObjType.isConstQualified();
2797 ObjType = Field->getType();
2798 if (WasConstQualified && !Field->isMutable())
2799 ObjType.addConst();
2800
2801 if (ObjType.isVolatileQualified()) {
2802 if (Info.getLangOpts().CPlusPlus) {
2803 // FIXME: Include a description of the path to the volatile subobject.
2804 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2805 << handler.AccessKind << 2 << Field;
2806 Info.Note(Field->getLocation(), diag::note_declared_at);
2807 } else {
2808 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2809 }
2810 return handler.failed();
2811 }
2812
2813 LastField = Field;
2814 } else {
2815 // Next subobject is a base class.
2816 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2817 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2818 O = &O->getStructBase(getBaseIndex(Derived, Base));
2819
2820 bool WasConstQualified = ObjType.isConstQualified();
2821 ObjType = Info.Ctx.getRecordType(Base);
2822 if (WasConstQualified)
2823 ObjType.addConst();
2824 }
2825 }
2826}
2827
2828namespace {
2829struct ExtractSubobjectHandler {
2830 EvalInfo &Info;
2831 APValue &Result;
2832
2833 static const AccessKinds AccessKind = AK_Read;
2834
2835 typedef bool result_type;
2836 bool failed() { return false; }
2837 bool found(APValue &Subobj, QualType SubobjType) {
2838 Result = Subobj;
2839 return true;
2840 }
2841 bool found(APSInt &Value, QualType SubobjType) {
2842 Result = APValue(Value);
2843 return true;
2844 }
2845 bool found(APFloat &Value, QualType SubobjType) {
2846 Result = APValue(Value);
2847 return true;
2848 }
2849 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2850 Result = APValue(extractStringLiteralCharacter(
2851 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2852 return true;
2853 }
2854};
2855} // end anonymous namespace
2856
2857const AccessKinds ExtractSubobjectHandler::AccessKind;
2858
2859/// Extract the designated sub-object of an rvalue.
2860static bool extractSubobject(EvalInfo &Info, const Expr *E,
2861 const CompleteObject &Obj,
2862 const SubobjectDesignator &Sub,
2863 APValue &Result) {
2864 ExtractSubobjectHandler Handler = { Info, Result };
2865 return findSubobject(Info, E, Obj, Sub, Handler);
2866}
2867
2868namespace {
2869struct ModifySubobjectHandler {
2870 EvalInfo &Info;
2871 APValue &NewVal;
2872 const Expr *E;
2873
2874 typedef bool result_type;
2875 static const AccessKinds AccessKind = AK_Assign;
2876
2877 bool checkConst(QualType QT) {
2878 // Assigning to a const object has undefined behavior.
2879 if (QT.isConstQualified()) {
2880 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2881 return false;
2882 }
2883 return true;
2884 }
2885
2886 bool failed() { return false; }
2887 bool found(APValue &Subobj, QualType SubobjType) {
2888 if (!checkConst(SubobjType))
2889 return false;
2890 // We've been given ownership of NewVal, so just swap it in.
2891 Subobj.swap(NewVal);
2892 return true;
2893 }
2894 bool found(APSInt &Value, QualType SubobjType) {
2895 if (!checkConst(SubobjType))
2896 return false;
2897 if (!NewVal.isInt()) {
2898 // Maybe trying to write a cast pointer value into a complex?
2899 Info.FFDiag(E);
2900 return false;
2901 }
2902 Value = NewVal.getInt();
2903 return true;
2904 }
2905 bool found(APFloat &Value, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2907 return false;
2908 Value = NewVal.getFloat();
2909 return true;
2910 }
2911 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2912 llvm_unreachable("shouldn't encounter string elements with ExpandArrays")::llvm::llvm_unreachable_internal("shouldn't encounter string elements with ExpandArrays"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 2912)
;
2913 }
2914};
2915} // end anonymous namespace
2916
2917const AccessKinds ModifySubobjectHandler::AccessKind;
2918
2919/// Update the designated sub-object of an rvalue to the given value.
2920static bool modifySubobject(EvalInfo &Info, const Expr *E,
2921 const CompleteObject &Obj,
2922 const SubobjectDesignator &Sub,
2923 APValue &NewVal) {
2924 ModifySubobjectHandler Handler = { Info, NewVal, E };
2925 return findSubobject(Info, E, Obj, Sub, Handler);
2926}
2927
2928/// Find the position where two subobject designators diverge, or equivalently
2929/// the length of the common initial subsequence.
2930static unsigned FindDesignatorMismatch(QualType ObjType,
2931 const SubobjectDesignator &A,
2932 const SubobjectDesignator &B,
2933 bool &WasArrayIndex) {
2934 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2935 for (/**/; I != N; ++I) {
2936 if (!ObjType.isNull() &&
2937 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2938 // Next subobject is an array element.
2939 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2940 WasArrayIndex = true;
2941 return I;
2942 }
2943 if (ObjType->isAnyComplexType())
2944 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2945 else
2946 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2947 } else {
2948 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2949 WasArrayIndex = false;
2950 return I;
2951 }
2952 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2953 // Next subobject is a field.
2954 ObjType = FD->getType();
2955 else
2956 // Next subobject is a base class.
2957 ObjType = QualType();
2958 }
2959 }
2960 WasArrayIndex = false;
2961 return I;
2962}
2963
2964/// Determine whether the given subobject designators refer to elements of the
2965/// same array object.
2966static bool AreElementsOfSameArray(QualType ObjType,
2967 const SubobjectDesignator &A,
2968 const SubobjectDesignator &B) {
2969 if (A.Entries.size() != B.Entries.size())
2970 return false;
2971
2972 bool IsArray = A.MostDerivedIsArrayElement;
2973 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2974 // A is a subobject of the array element.
2975 return false;
2976
2977 // If A (and B) designates an array element, the last entry will be the array
2978 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2979 // of length 1' case, and the entire path must match.
2980 bool WasArrayIndex;
2981 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2982 return CommonLength >= A.Entries.size() - IsArray;
2983}
2984
2985/// Find the complete object to which an LValue refers.
2986static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2987 AccessKinds AK, const LValue &LVal,
2988 QualType LValType) {
2989 if (!LVal.Base) {
2990 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2991 return CompleteObject();
2992 }
2993
2994 CallStackFrame *Frame = nullptr;
2995 if (LVal.CallIndex) {
2996 Frame = Info.getCallFrame(LVal.CallIndex);
2997 if (!Frame) {
2998 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2999 << AK << LVal.Base.is<const ValueDecl*>();
3000 NoteLValueLocation(Info, LVal.Base);
3001 return CompleteObject();
3002 }
3003 }
3004
3005 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3006 // is not a constant expression (even if the object is non-volatile). We also
3007 // apply this rule to C++98, in order to conform to the expected 'volatile'
3008 // semantics.
3009 if (LValType.isVolatileQualified()) {
3010 if (Info.getLangOpts().CPlusPlus)
3011 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3012 << AK << LValType;
3013 else
3014 Info.FFDiag(E);
3015 return CompleteObject();
3016 }
3017
3018 // Compute value storage location and type of base object.
3019 APValue *BaseVal = nullptr;
3020 QualType BaseType = getType(LVal.Base);
3021
3022 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3023 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3024 // In C++11, constexpr, non-volatile variables initialized with constant
3025 // expressions are constant expressions too. Inside constexpr functions,
3026 // parameters are constant expressions even if they're non-const.
3027 // In C++1y, objects local to a constant expression (those with a Frame) are
3028 // both readable and writable inside constant expressions.
3029 // In C, such things can also be folded, although they are not ICEs.
3030 const VarDecl *VD = dyn_cast<VarDecl>(D);
3031 if (VD) {
3032 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3033 VD = VDef;
3034 }
3035 if (!VD || VD->isInvalidDecl()) {
3036 Info.FFDiag(E);
3037 return CompleteObject();
3038 }
3039
3040 // Accesses of volatile-qualified objects are not allowed.
3041 if (BaseType.isVolatileQualified()) {
3042 if (Info.getLangOpts().CPlusPlus) {
3043 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3044 << AK << 1 << VD;
3045 Info.Note(VD->getLocation(), diag::note_declared_at);
3046 } else {
3047 Info.FFDiag(E);
3048 }
3049 return CompleteObject();
3050 }
3051
3052 // Unless we're looking at a local variable or argument in a constexpr call,
3053 // the variable we're reading must be const.
3054 if (!Frame) {
3055 if (Info.getLangOpts().CPlusPlus14 &&
3056 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3057 // OK, we can read and modify an object if we're in the process of
3058 // evaluating its initializer, because its lifetime began in this
3059 // evaluation.
3060 } else if (AK != AK_Read) {
3061 // All the remaining cases only permit reading.
3062 Info.FFDiag(E, diag::note_constexpr_modify_global);
3063 return CompleteObject();
3064 } else if (VD->isConstexpr()) {
3065 // OK, we can read this variable.
3066 } else if (BaseType->isIntegralOrEnumerationType()) {
3067 // In OpenCL if a variable is in constant address space it is a const value.
3068 if (!(BaseType.isConstQualified() ||
3069 (Info.getLangOpts().OpenCL &&
3070 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3071 if (Info.getLangOpts().CPlusPlus) {
3072 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3073 Info.Note(VD->getLocation(), diag::note_declared_at);
3074 } else {
3075 Info.FFDiag(E);
3076 }
3077 return CompleteObject();
3078 }
3079 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3080 // We support folding of const floating-point types, in order to make
3081 // static const data members of such types (supported as an extension)
3082 // more useful.
3083 if (Info.getLangOpts().CPlusPlus11) {
3084 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3085 Info.Note(VD->getLocation(), diag::note_declared_at);
3086 } else {
3087 Info.CCEDiag(E);
3088 }
3089 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3090 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3091 // Keep evaluating to see what we can do.
3092 } else {
3093 // FIXME: Allow folding of values of any literal type in all languages.
3094 if (Info.checkingPotentialConstantExpression() &&
3095 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3096 // The definition of this variable could be constexpr. We can't
3097 // access it right now, but may be able to in future.
3098 } else if (Info.getLangOpts().CPlusPlus11) {
3099 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3100 Info.Note(VD->getLocation(), diag::note_declared_at);
3101 } else {
3102 Info.FFDiag(E);
3103 }
3104 return CompleteObject();
3105 }
3106 }
3107
3108 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3109 return CompleteObject();
3110 } else {
3111 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3112
3113 if (!Frame) {
3114 if (const MaterializeTemporaryExpr *MTE =
3115 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3116 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3117, __extension__ __PRETTY_FUNCTION__))
3117 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3117, __extension__ __PRETTY_FUNCTION__))
;
3118
3119 // Per C++1y [expr.const]p2:
3120 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3121 // - a [...] glvalue of integral or enumeration type that refers to
3122 // a non-volatile const object [...]
3123 // [...]
3124 // - a [...] glvalue of literal type that refers to a non-volatile
3125 // object whose lifetime began within the evaluation of e.
3126 //
3127 // C++11 misses the 'began within the evaluation of e' check and
3128 // instead allows all temporaries, including things like:
3129 // int &&r = 1;
3130 // int x = ++r;
3131 // constexpr int k = r;
3132 // Therefore we use the C++1y rules in C++11 too.
3133 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3134 const ValueDecl *ED = MTE->getExtendingDecl();
3135 if (!(BaseType.isConstQualified() &&
3136 BaseType->isIntegralOrEnumerationType()) &&
3137 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3138 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3139 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3140 return CompleteObject();
3141 }
3142
3143 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3144 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3144, __extension__ __PRETTY_FUNCTION__))
;
3145 } else {
3146 Info.FFDiag(E);
3147 return CompleteObject();
3148 }
3149 } else {
3150 BaseVal = Frame->getTemporary(Base);
3151 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3151, __extension__ __PRETTY_FUNCTION__))
;
3152 }
3153
3154 // Volatile temporary objects cannot be accessed in constant expressions.
3155 if (BaseType.isVolatileQualified()) {
3156 if (Info.getLangOpts().CPlusPlus) {
3157 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3158 << AK << 0;
3159 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3160 } else {
3161 Info.FFDiag(E);
3162 }
3163 return CompleteObject();
3164 }
3165 }
3166
3167 // During the construction of an object, it is not yet 'const'.
3168 // FIXME: This doesn't do quite the right thing for const subobjects of the
3169 // object under construction.
3170 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3171 BaseType = Info.Ctx.getCanonicalType(BaseType);
3172 BaseType.removeLocalConst();
3173 }
3174
3175 // In C++1y, we can't safely access any mutable state when we might be
3176 // evaluating after an unmodeled side effect.
3177 //
3178 // FIXME: Not all local state is mutable. Allow local constant subobjects
3179 // to be read here (but take care with 'mutable' fields).
3180 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3181 Info.EvalStatus.HasSideEffects) ||
3182 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3183 return CompleteObject();
3184
3185 return CompleteObject(BaseVal, BaseType);
3186}
3187
3188/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3189/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3190/// glvalue referred to by an entity of reference type.
3191///
3192/// \param Info - Information about the ongoing evaluation.
3193/// \param Conv - The expression for which we are performing the conversion.
3194/// Used for diagnostics.
3195/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3196/// case of a non-class type).
3197/// \param LVal - The glvalue on which we are attempting to perform this action.
3198/// \param RVal - The produced value will be placed here.
3199static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3200 QualType Type,
3201 const LValue &LVal, APValue &RVal) {
3202 if (LVal.Designator.Invalid)
3203 return false;
3204
3205 // Check for special cases where there is no existing APValue to look at.
3206 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3207 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3208 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3209 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3210 // initializer until now for such expressions. Such an expression can't be
3211 // an ICE in C, so this only matters for fold.
3212 if (Type.isVolatileQualified()) {
3213 Info.FFDiag(Conv);
3214 return false;
3215 }
3216 APValue Lit;
3217 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3218 return false;
3219 CompleteObject LitObj(&Lit, Base->getType());
3220 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3221 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3222 // We represent a string literal array as an lvalue pointing at the
3223 // corresponding expression, rather than building an array of chars.
3224 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3225 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3226 CompleteObject StrObj(&Str, Base->getType());
3227 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3228 }
3229 }
3230
3231 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3232 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3233}
3234
3235/// Perform an assignment of Val to LVal. Takes ownership of Val.
3236static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3237 QualType LValType, APValue &Val) {
3238 if (LVal.Designator.Invalid)
3239 return false;
3240
3241 if (!Info.getLangOpts().CPlusPlus14) {
3242 Info.FFDiag(E);
3243 return false;
3244 }
3245
3246 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3247 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3248}
3249
3250static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3251 return T->isSignedIntegerType() &&
3252 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3253}
3254
3255namespace {
3256struct CompoundAssignSubobjectHandler {
3257 EvalInfo &Info;
3258 const Expr *E;
3259 QualType PromotedLHSType;
3260 BinaryOperatorKind Opcode;
3261 const APValue &RHS;
3262
3263 static const AccessKinds AccessKind = AK_Assign;
3264
3265 typedef bool result_type;
3266
3267 bool checkConst(QualType QT) {
3268 // Assigning to a const object has undefined behavior.
3269 if (QT.isConstQualified()) {
3270 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3271 return false;
3272 }
3273 return true;
3274 }
3275
3276 bool failed() { return false; }
3277 bool found(APValue &Subobj, QualType SubobjType) {
3278 switch (Subobj.getKind()) {
3279 case APValue::Int:
3280 return found(Subobj.getInt(), SubobjType);
3281 case APValue::Float:
3282 return found(Subobj.getFloat(), SubobjType);
3283 case APValue::ComplexInt:
3284 case APValue::ComplexFloat:
3285 // FIXME: Implement complex compound assignment.
3286 Info.FFDiag(E);
3287 return false;
3288 case APValue::LValue:
3289 return foundPointer(Subobj, SubobjType);
3290 default:
3291 // FIXME: can this happen?
3292 Info.FFDiag(E);
3293 return false;
3294 }
3295 }
3296 bool found(APSInt &Value, QualType SubobjType) {
3297 if (!checkConst(SubobjType))
3298 return false;
3299
3300 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3301 // We don't support compound assignment on integer-cast-to-pointer
3302 // values.
3303 Info.FFDiag(E);
3304 return false;
3305 }
3306
3307 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3308 SubobjType, Value);
3309 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3310 return false;
3311 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3312 return true;
3313 }
3314 bool found(APFloat &Value, QualType SubobjType) {
3315 return checkConst(SubobjType) &&
3316 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3317 Value) &&
3318 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3319 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3320 }
3321 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3322 if (!checkConst(SubobjType))
3323 return false;
3324
3325 QualType PointeeType;
3326 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3327 PointeeType = PT->getPointeeType();
3328
3329 if (PointeeType.isNull() || !RHS.isInt() ||
3330 (Opcode != BO_Add && Opcode != BO_Sub)) {
3331 Info.FFDiag(E);
3332 return false;
3333 }
3334
3335 APSInt Offset = RHS.getInt();
3336 if (Opcode == BO_Sub)
3337 negateAsSigned(Offset);
3338
3339 LValue LVal;
3340 LVal.setFrom(Info.Ctx, Subobj);
3341 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3342 return false;
3343 LVal.moveInto(Subobj);
3344 return true;
3345 }
3346 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3347 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3347)
;
3348 }
3349};
3350} // end anonymous namespace
3351
3352const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3353
3354/// Perform a compound assignment of LVal <op>= RVal.
3355static bool handleCompoundAssignment(
3356 EvalInfo &Info, const Expr *E,
3357 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3358 BinaryOperatorKind Opcode, const APValue &RVal) {
3359 if (LVal.Designator.Invalid)
3360 return false;
3361
3362 if (!Info.getLangOpts().CPlusPlus14) {
3363 Info.FFDiag(E);
3364 return false;
3365 }
3366
3367 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3368 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3369 RVal };
3370 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3371}
3372
3373namespace {
3374struct IncDecSubobjectHandler {
3375 EvalInfo &Info;
3376 const Expr *E;
3377 AccessKinds AccessKind;
3378 APValue *Old;
3379
3380 typedef bool result_type;
3381
3382 bool checkConst(QualType QT) {
3383 // Assigning to a const object has undefined behavior.
3384 if (QT.isConstQualified()) {
3385 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3386 return false;
3387 }
3388 return true;
3389 }
3390
3391 bool failed() { return false; }
3392 bool found(APValue &Subobj, QualType SubobjType) {
3393 // Stash the old value. Also clear Old, so we don't clobber it later
3394 // if we're post-incrementing a complex.
3395 if (Old) {
3396 *Old = Subobj;
3397 Old = nullptr;
3398 }
3399
3400 switch (Subobj.getKind()) {
3401 case APValue::Int:
3402 return found(Subobj.getInt(), SubobjType);
3403 case APValue::Float:
3404 return found(Subobj.getFloat(), SubobjType);
3405 case APValue::ComplexInt:
3406 return found(Subobj.getComplexIntReal(),
3407 SubobjType->castAs<ComplexType>()->getElementType()
3408 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3409 case APValue::ComplexFloat:
3410 return found(Subobj.getComplexFloatReal(),
3411 SubobjType->castAs<ComplexType>()->getElementType()
3412 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3413 case APValue::LValue:
3414 return foundPointer(Subobj, SubobjType);
3415 default:
3416 // FIXME: can this happen?
3417 Info.FFDiag(E);
3418 return false;
3419 }
3420 }
3421 bool found(APSInt &Value, QualType SubobjType) {
3422 if (!checkConst(SubobjType))
3423 return false;
3424
3425 if (!SubobjType->isIntegerType()) {
3426 // We don't support increment / decrement on integer-cast-to-pointer
3427 // values.
3428 Info.FFDiag(E);
3429 return false;
3430 }
3431
3432 if (Old) *Old = APValue(Value);
3433
3434 // bool arithmetic promotes to int, and the conversion back to bool
3435 // doesn't reduce mod 2^n, so special-case it.
3436 if (SubobjType->isBooleanType()) {
3437 if (AccessKind == AK_Increment)
3438 Value = 1;
3439 else
3440 Value = !Value;
3441 return true;
3442 }
3443
3444 bool WasNegative = Value.isNegative();
3445 if (AccessKind == AK_Increment) {
3446 ++Value;
3447
3448 if (!WasNegative && Value.isNegative() &&
3449 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3450 APSInt ActualValue(Value, /*IsUnsigned*/true);
3451 return HandleOverflow(Info, E, ActualValue, SubobjType);
3452 }
3453 } else {
3454 --Value;
3455
3456 if (WasNegative && !Value.isNegative() &&
3457 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3458 unsigned BitWidth = Value.getBitWidth();
3459 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3460 ActualValue.setBit(BitWidth);
3461 return HandleOverflow(Info, E, ActualValue, SubobjType);
3462 }
3463 }
3464 return true;
3465 }
3466 bool found(APFloat &Value, QualType SubobjType) {
3467 if (!checkConst(SubobjType))
3468 return false;
3469
3470 if (Old) *Old = APValue(Value);
3471
3472 APFloat One(Value.getSemantics(), 1);
3473 if (AccessKind == AK_Increment)
3474 Value.add(One, APFloat::rmNearestTiesToEven);
3475 else
3476 Value.subtract(One, APFloat::rmNearestTiesToEven);
3477 return true;
3478 }
3479 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3480 if (!checkConst(SubobjType))
3481 return false;
3482
3483 QualType PointeeType;
3484 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3485 PointeeType = PT->getPointeeType();
3486 else {
3487 Info.FFDiag(E);
3488 return false;
3489 }
3490
3491 LValue LVal;
3492 LVal.setFrom(Info.Ctx, Subobj);
3493 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3494 AccessKind == AK_Increment ? 1 : -1))
3495 return false;
3496 LVal.moveInto(Subobj);
3497 return true;
3498 }
3499 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3500 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3500)
;
3501 }
3502};
3503} // end anonymous namespace
3504
3505/// Perform an increment or decrement on LVal.
3506static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3507 QualType LValType, bool IsIncrement, APValue *Old) {
3508 if (LVal.Designator.Invalid)
3509 return false;
3510
3511 if (!Info.getLangOpts().CPlusPlus14) {
3512 Info.FFDiag(E);
3513 return false;
3514 }
3515
3516 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3517 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3518 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3519 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3520}
3521
3522/// Build an lvalue for the object argument of a member function call.
3523static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3524 LValue &This) {
3525 if (Object->getType()->isPointerType())
3526 return EvaluatePointer(Object, This, Info);
3527
3528 if (Object->isGLValue())
3529 return EvaluateLValue(Object, This, Info);
3530
3531 if (Object->getType()->isLiteralType(Info.Ctx))
3532 return EvaluateTemporary(Object, This, Info);
3533
3534 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3535 return false;
3536}
3537
3538/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3539/// lvalue referring to the result.
3540///
3541/// \param Info - Information about the ongoing evaluation.
3542/// \param LV - An lvalue referring to the base of the member pointer.
3543/// \param RHS - The member pointer expression.
3544/// \param IncludeMember - Specifies whether the member itself is included in
3545/// the resulting LValue subobject designator. This is not possible when
3546/// creating a bound member function.
3547/// \return The field or method declaration to which the member pointer refers,
3548/// or 0 if evaluation fails.
3549static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3550 QualType LVType,
3551 LValue &LV,
3552 const Expr *RHS,
3553 bool IncludeMember = true) {
3554 MemberPtr MemPtr;
3555 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3556 return nullptr;
3557
3558 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3559 // member value, the behavior is undefined.
3560 if (!MemPtr.getDecl()) {
3561 // FIXME: Specific diagnostic.
3562 Info.FFDiag(RHS);
3563 return nullptr;
3564 }
3565
3566 if (MemPtr.isDerivedMember()) {
3567 // This is a member of some derived class. Truncate LV appropriately.
3568 // The end of the derived-to-base path for the base object must match the
3569 // derived-to-base path for the member pointer.
3570 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3571 LV.Designator.Entries.size()) {
3572 Info.FFDiag(RHS);
3573 return nullptr;
3574 }
3575 unsigned PathLengthToMember =
3576 LV.Designator.Entries.size() - MemPtr.Path.size();
3577 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3578 const CXXRecordDecl *LVDecl = getAsBaseClass(
3579 LV.Designator.Entries[PathLengthToMember + I]);
3580 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3581 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3582 Info.FFDiag(RHS);
3583 return nullptr;
3584 }
3585 }
3586
3587 // Truncate the lvalue to the appropriate derived class.
3588 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3589 PathLengthToMember))
3590 return nullptr;
3591 } else if (!MemPtr.Path.empty()) {
3592 // Extend the LValue path with the member pointer's path.
3593 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3594 MemPtr.Path.size() + IncludeMember);
3595
3596 // Walk down to the appropriate base class.
3597 if (const PointerType *PT = LVType->getAs<PointerType>())
3598 LVType = PT->getPointeeType();
3599 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3600 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3600, __extension__ __PRETTY_FUNCTION__))
;
3601 // The first class in the path is that of the lvalue.
3602 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3603 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3604 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3605 return nullptr;
3606 RD = Base;
3607 }
3608 // Finally cast to the class containing the member.
3609 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3610 MemPtr.getContainingRecord()))
3611 return nullptr;
3612 }
3613
3614 // Add the member. Note that we cannot build bound member functions here.
3615 if (IncludeMember) {
3616 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3617 if (!HandleLValueMember(Info, RHS, LV, FD))
3618 return nullptr;
3619 } else if (const IndirectFieldDecl *IFD =
3620 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3621 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3622 return nullptr;
3623 } else {
3624 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3624)
;
3625 }
3626 }
3627
3628 return MemPtr.getDecl();
3629}
3630
3631static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3632 const BinaryOperator *BO,
3633 LValue &LV,
3634 bool IncludeMember = true) {
3635 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3635, __extension__ __PRETTY_FUNCTION__))
;
3636
3637 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3638 if (Info.noteFailure()) {
3639 MemberPtr MemPtr;
3640 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3641 }
3642 return nullptr;
3643 }
3644
3645 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3646 BO->getRHS(), IncludeMember);
3647}
3648
3649/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3650/// the provided lvalue, which currently refers to the base object.
3651static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3652 LValue &Result) {
3653 SubobjectDesignator &D = Result.Designator;
3654 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3655 return false;
3656
3657 QualType TargetQT = E->getType();
3658 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3659 TargetQT = PT->getPointeeType();
3660
3661 // Check this cast lands within the final derived-to-base subobject path.
3662 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3663 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3664 << D.MostDerivedType << TargetQT;
3665 return false;
3666 }
3667
3668 // Check the type of the final cast. We don't need to check the path,
3669 // since a cast can only be formed if the path is unique.
3670 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3671 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3672 const CXXRecordDecl *FinalType;
3673 if (NewEntriesSize == D.MostDerivedPathLength)
3674 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3675 else
3676 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3677 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3678 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3679 << D.MostDerivedType << TargetQT;
3680 return false;
3681 }
3682
3683 // Truncate the lvalue to the appropriate derived class.
3684 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3685}
3686
3687namespace {
3688enum EvalStmtResult {
3689 /// Evaluation failed.
3690 ESR_Failed,
3691 /// Hit a 'return' statement.
3692 ESR_Returned,
3693 /// Evaluation succeeded.
3694 ESR_Succeeded,
3695 /// Hit a 'continue' statement.
3696 ESR_Continue,
3697 /// Hit a 'break' statement.
3698 ESR_Break,
3699 /// Still scanning for 'case' or 'default' statement.
3700 ESR_CaseNotFound
3701};
3702}
3703
3704static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3705 // We don't need to evaluate the initializer for a static local.
3706 if (!VD->hasLocalStorage())
3707 return true;
3708
3709 LValue Result;
3710 Result.set(VD, Info.CurrentCall->Index);
3711 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3712
3713 const Expr *InitE = VD->getInit();
3714 if (!InitE) {
3715 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3716 << false << VD->getType();
3717 Val = APValue();
3718 return false;
3719 }
3720
3721 if (InitE->isValueDependent())
3722 return false;
3723
3724 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3725 // Wipe out any partially-computed value, to allow tracking that this
3726 // evaluation failed.
3727 Val = APValue();
3728 return false;
3729 }
3730
3731 return true;
3732}
3733
3734static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3735 bool OK = true;
3736
3737 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3738 OK &= EvaluateVarDecl(Info, VD);
3739
3740 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3741 for (auto *BD : DD->bindings())
3742 if (auto *VD = BD->getHoldingVar())
3743 OK &= EvaluateDecl(Info, VD);
3744
3745 return OK;
3746}
3747
3748
3749/// Evaluate a condition (either a variable declaration or an expression).
3750static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3751 const Expr *Cond, bool &Result) {
3752 FullExpressionRAII Scope(Info);
3753 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3754 return false;
3755 return EvaluateAsBooleanCondition(Cond, Result, Info);
3756}
3757
3758namespace {
3759/// \brief A location where the result (returned value) of evaluating a
3760/// statement should be stored.
3761struct StmtResult {
3762 /// The APValue that should be filled in with the returned value.
3763 APValue &Value;
3764 /// The location containing the result, if any (used to support RVO).
3765 const LValue *Slot;
3766};
3767}
3768
3769static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3770 const Stmt *S,
3771 const SwitchCase *SC = nullptr);
3772
3773/// Evaluate the body of a loop, and translate the result as appropriate.
3774static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3775 const Stmt *Body,
3776 const SwitchCase *Case = nullptr) {
3777 BlockScopeRAII Scope(Info);
3778 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3779 case ESR_Break:
3780 return ESR_Succeeded;
3781 case ESR_Succeeded:
3782 case ESR_Continue:
3783 return ESR_Continue;
3784 case ESR_Failed:
3785 case ESR_Returned:
3786 case ESR_CaseNotFound:
3787 return ESR;
3788 }
3789 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3789)
;
3790}
3791
3792/// Evaluate a switch statement.
3793static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3794 const SwitchStmt *SS) {
3795 BlockScopeRAII Scope(Info);
3796
3797 // Evaluate the switch condition.
3798 APSInt Value;
3799 {
3800 FullExpressionRAII Scope(Info);
3801 if (const Stmt *Init = SS->getInit()) {
3802 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3803 if (ESR != ESR_Succeeded)
3804 return ESR;
3805 }
3806 if (SS->getConditionVariable() &&
3807 !EvaluateDecl(Info, SS->getConditionVariable()))
3808 return ESR_Failed;
3809 if (!EvaluateInteger(SS->getCond(), Value, Info))
3810 return ESR_Failed;
3811 }
3812
3813 // Find the switch case corresponding to the value of the condition.
3814 // FIXME: Cache this lookup.
3815 const SwitchCase *Found = nullptr;
3816 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3817 SC = SC->getNextSwitchCase()) {
3818 if (isa<DefaultStmt>(SC)) {
3819 Found = SC;
3820 continue;
3821 }
3822
3823 const CaseStmt *CS = cast<CaseStmt>(SC);
3824 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3825 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3826 : LHS;
3827 if (LHS <= Value && Value <= RHS) {
3828 Found = SC;
3829 break;
3830 }
3831 }
3832
3833 if (!Found)
3834 return ESR_Succeeded;
3835
3836 // Search the switch body for the switch case and evaluate it from there.
3837 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3838 case ESR_Break:
3839 return ESR_Succeeded;
3840 case ESR_Succeeded:
3841 case ESR_Continue:
3842 case ESR_Failed:
3843 case ESR_Returned:
3844 return ESR;
3845 case ESR_CaseNotFound:
3846 // This can only happen if the switch case is nested within a statement
3847 // expression. We have no intention of supporting that.
3848 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3849 return ESR_Failed;
3850 }
3851 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 3851)
;
3852}
3853
3854// Evaluate a statement.
3855static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3856 const Stmt *S, const SwitchCase *Case) {
3857 if (!Info.nextStep(S))
3858 return ESR_Failed;
3859
3860 // If we're hunting down a 'case' or 'default' label, recurse through
3861 // substatements until we hit the label.
3862 if (Case) {
3863 // FIXME: We don't start the lifetime of objects whose initialization we
3864 // jump over. However, such objects must be of class type with a trivial
3865 // default constructor that initialize all subobjects, so must be empty,
3866 // so this almost never matters.
3867 switch (S->getStmtClass()) {
3868 case Stmt::CompoundStmtClass:
3869 // FIXME: Precompute which substatement of a compound statement we
3870 // would jump to, and go straight there rather than performing a
3871 // linear scan each time.
3872 case Stmt::LabelStmtClass:
3873 case Stmt::AttributedStmtClass:
3874 case Stmt::DoStmtClass:
3875 break;
3876
3877 case Stmt::CaseStmtClass:
3878 case Stmt::DefaultStmtClass:
3879 if (Case == S)
3880 Case = nullptr;
3881 break;
3882
3883 case Stmt::IfStmtClass: {
3884 // FIXME: Precompute which side of an 'if' we would jump to, and go
3885 // straight there rather than scanning both sides.
3886 const IfStmt *IS = cast<IfStmt>(S);
3887
3888 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3889 // preceded by our switch label.
3890 BlockScopeRAII Scope(Info);
3891
3892 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3893 if (ESR != ESR_CaseNotFound || !IS->getElse())
3894 return ESR;
3895 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3896 }
3897
3898 case Stmt::WhileStmtClass: {
3899 EvalStmtResult ESR =
3900 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3901 if (ESR != ESR_Continue)
3902 return ESR;
3903 break;
3904 }
3905
3906 case Stmt::ForStmtClass: {
3907 const ForStmt *FS = cast<ForStmt>(S);
3908 EvalStmtResult ESR =
3909 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3910 if (ESR != ESR_Continue)
3911 return ESR;
3912 if (FS->getInc()) {
3913 FullExpressionRAII IncScope(Info);
3914 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3915 return ESR_Failed;
3916 }
3917 break;
3918 }
3919
3920 case Stmt::DeclStmtClass:
3921 // FIXME: If the variable has initialization that can't be jumped over,
3922 // bail out of any immediately-surrounding compound-statement too.
3923 default:
3924 return ESR_CaseNotFound;
3925 }
3926 }
3927
3928 switch (S->getStmtClass()) {
3929 default:
3930 if (const Expr *E = dyn_cast<Expr>(S)) {
3931 // Don't bother evaluating beyond an expression-statement which couldn't
3932 // be evaluated.
3933 FullExpressionRAII Scope(Info);
3934 if (!EvaluateIgnoredValue(Info, E))
3935 return ESR_Failed;
3936 return ESR_Succeeded;
3937 }
3938
3939 Info.FFDiag(S->getLocStart());
3940 return ESR_Failed;
3941
3942 case Stmt::NullStmtClass:
3943 return ESR_Succeeded;
3944
3945 case Stmt::DeclStmtClass: {
3946 const DeclStmt *DS = cast<DeclStmt>(S);
3947 for (const auto *DclIt : DS->decls()) {
3948 // Each declaration initialization is its own full-expression.
3949 // FIXME: This isn't quite right; if we're performing aggregate
3950 // initialization, each braced subexpression is its own full-expression.
3951 FullExpressionRAII Scope(Info);
3952 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3953 return ESR_Failed;
3954 }
3955 return ESR_Succeeded;
3956 }
3957
3958 case Stmt::ReturnStmtClass: {
3959 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3960 FullExpressionRAII Scope(Info);
3961 if (RetExpr &&
3962 !(Result.Slot
3963 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3964 : Evaluate(Result.Value, Info, RetExpr)))
3965 return ESR_Failed;
3966 return ESR_Returned;
3967 }
3968
3969 case Stmt::CompoundStmtClass: {
3970 BlockScopeRAII Scope(Info);
3971
3972 const CompoundStmt *CS = cast<CompoundStmt>(S);
3973 for (const auto *BI : CS->body()) {
3974 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3975 if (ESR == ESR_Succeeded)
3976 Case = nullptr;
3977 else if (ESR != ESR_CaseNotFound)
3978 return ESR;
3979 }
3980 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3981 }
3982
3983 case Stmt::IfStmtClass: {
3984 const IfStmt *IS = cast<IfStmt>(S);
3985
3986 // Evaluate the condition, as either a var decl or as an expression.
3987 BlockScopeRAII Scope(Info);
3988 if (const Stmt *Init = IS->getInit()) {
3989 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3990 if (ESR != ESR_Succeeded)
3991 return ESR;
3992 }
3993 bool Cond;
3994 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3995 return ESR_Failed;
3996
3997 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3998 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3999 if (ESR != ESR_Succeeded)
4000 return ESR;
4001 }
4002 return ESR_Succeeded;
4003 }
4004
4005 case Stmt::WhileStmtClass: {
4006 const WhileStmt *WS = cast<WhileStmt>(S);
4007 while (true) {
4008 BlockScopeRAII Scope(Info);
4009 bool Continue;
4010 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4011 Continue))
4012 return ESR_Failed;
4013 if (!Continue)
4014 break;
4015
4016 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4017 if (ESR != ESR_Continue)
4018 return ESR;
4019 }
4020 return ESR_Succeeded;
4021 }
4022
4023 case Stmt::DoStmtClass: {
4024 const DoStmt *DS = cast<DoStmt>(S);
4025 bool Continue;
4026 do {
4027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4028 if (ESR != ESR_Continue)
4029 return ESR;
4030 Case = nullptr;
4031
4032 FullExpressionRAII CondScope(Info);
4033 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4034 return ESR_Failed;
4035 } while (Continue);
4036 return ESR_Succeeded;
4037 }
4038
4039 case Stmt::ForStmtClass: {
4040 const ForStmt *FS = cast<ForStmt>(S);
4041 BlockScopeRAII Scope(Info);
4042 if (FS->getInit()) {
4043 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4044 if (ESR != ESR_Succeeded)
4045 return ESR;
4046 }
4047 while (true) {
4048 BlockScopeRAII Scope(Info);
4049 bool Continue = true;
4050 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4051 FS->getCond(), Continue))
4052 return ESR_Failed;
4053 if (!Continue)
4054 break;
4055
4056 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4057 if (ESR != ESR_Continue)
4058 return ESR;
4059
4060 if (FS->getInc()) {
4061 FullExpressionRAII IncScope(Info);
4062 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4063 return ESR_Failed;
4064 }
4065 }
4066 return ESR_Succeeded;
4067 }
4068
4069 case Stmt::CXXForRangeStmtClass: {
4070 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4071 BlockScopeRAII Scope(Info);
4072
4073 // Initialize the __range variable.
4074 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4075 if (ESR != ESR_Succeeded)
4076 return ESR;
4077
4078 // Create the __begin and __end iterators.
4079 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4080 if (ESR != ESR_Succeeded)
4081 return ESR;
4082 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4083 if (ESR != ESR_Succeeded)
4084 return ESR;
4085
4086 while (true) {
4087 // Condition: __begin != __end.
4088 {
4089 bool Continue = true;
4090 FullExpressionRAII CondExpr(Info);
4091 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4092 return ESR_Failed;
4093 if (!Continue)
4094 break;
4095 }
4096
4097 // User's variable declaration, initialized by *__begin.
4098 BlockScopeRAII InnerScope(Info);
4099 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4100 if (ESR != ESR_Succeeded)
4101 return ESR;
4102
4103 // Loop body.
4104 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4105 if (ESR != ESR_Continue)
4106 return ESR;
4107
4108 // Increment: ++__begin
4109 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4110 return ESR_Failed;
4111 }
4112
4113 return ESR_Succeeded;
4114 }
4115
4116 case Stmt::SwitchStmtClass:
4117 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4118
4119 case Stmt::ContinueStmtClass:
4120 return ESR_Continue;
4121
4122 case Stmt::BreakStmtClass:
4123 return ESR_Break;
4124
4125 case Stmt::LabelStmtClass:
4126 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4127
4128 case Stmt::AttributedStmtClass:
4129 // As a general principle, C++11 attributes can be ignored without
4130 // any semantic impact.
4131 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4132 Case);
4133
4134 case Stmt::CaseStmtClass:
4135 case Stmt::DefaultStmtClass:
4136 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4137 }
4138}
4139
4140/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4141/// default constructor. If so, we'll fold it whether or not it's marked as
4142/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4143/// so we need special handling.
4144static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4145 const CXXConstructorDecl *CD,
4146 bool IsValueInitialization) {
4147 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4148 return false;
4149
4150 // Value-initialization does not call a trivial default constructor, so such a
4151 // call is a core constant expression whether or not the constructor is
4152 // constexpr.
4153 if (!CD->isConstexpr() && !IsValueInitialization) {
4154 if (Info.getLangOpts().CPlusPlus11) {
4155 // FIXME: If DiagDecl is an implicitly-declared special member function,
4156 // we should be much more explicit about why it's not constexpr.
4157 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4158 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4159 Info.Note(CD->getLocation(), diag::note_declared_at);
4160 } else {
4161 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4162 }
4163 }
4164 return true;
4165}
4166
4167/// CheckConstexprFunction - Check that a function can be called in a constant
4168/// expression.
4169static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4170 const FunctionDecl *Declaration,
4171 const FunctionDecl *Definition,
4172 const Stmt *Body) {
4173 // Potential constant expressions can contain calls to declared, but not yet
4174 // defined, constexpr functions.
4175 if (Info.checkingPotentialConstantExpression() && !Definition &&
4176 Declaration->isConstexpr())
4177 return false;
4178
4179 // Bail out with no diagnostic if the function declaration itself is invalid.
4180 // We will have produced a relevant diagnostic while parsing it.
4181 if (Declaration->isInvalidDecl())
4182 return false;
4183
4184 // Can we evaluate this function call?
4185 if (Definition && Definition->isConstexpr() &&
4186 !Definition->isInvalidDecl() && Body)
4187 return true;
4188
4189 if (Info.getLangOpts().CPlusPlus11) {
4190 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4191
4192 // If this function is not constexpr because it is an inherited
4193 // non-constexpr constructor, diagnose that directly.
4194 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4195 if (CD && CD->isInheritingConstructor()) {
4196 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4197 if (!Inherited->isConstexpr())
4198 DiagDecl = CD = Inherited;
4199 }
4200
4201 // FIXME: If DiagDecl is an implicitly-declared special member function
4202 // or an inheriting constructor, we should be much more explicit about why
4203 // it's not constexpr.
4204 if (CD && CD->isInheritingConstructor())
4205 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4206 << CD->getInheritedConstructor().getConstructor()->getParent();
4207 else
4208 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4209 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4210 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4211 } else {
4212 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4213 }
4214 return false;
4215}
4216
4217/// Determine if a class has any fields that might need to be copied by a
4218/// trivial copy or move operation.
4219static bool hasFields(const CXXRecordDecl *RD) {
4220 if (!RD || RD->isEmpty())
4221 return false;
4222 for (auto *FD : RD->fields()) {
4223 if (FD->isUnnamedBitfield())
4224 continue;
4225 return true;
4226 }
4227 for (auto &Base : RD->bases())
4228 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4229 return true;
4230 return false;
4231}
4232
4233namespace {
4234typedef SmallVector<APValue, 8> ArgVector;
4235}
4236
4237/// EvaluateArgs - Evaluate the arguments to a function call.
4238static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4239 EvalInfo &Info) {
4240 bool Success = true;
4241 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4242 I != E; ++I) {
4243 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4244 // If we're checking for a potential constant expression, evaluate all
4245 // initializers even if some of them fail.
4246 if (!Info.noteFailure())
4247 return false;
4248 Success = false;
4249 }
4250 }
4251 return Success;
4252}
4253
4254/// Evaluate a function call.
4255static bool HandleFunctionCall(SourceLocation CallLoc,
4256 const FunctionDecl *Callee, const LValue *This,
4257 ArrayRef<const Expr*> Args, const Stmt *Body,
4258 EvalInfo &Info, APValue &Result,
4259 const LValue *ResultSlot) {
4260 ArgVector ArgValues(Args.size());
4261 if (!EvaluateArgs(Args, ArgValues, Info))
4262 return false;
4263
4264 if (!Info.CheckCallLimit(CallLoc))
4265 return false;
4266
4267 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4268
4269 // For a trivial copy or move assignment, perform an APValue copy. This is
4270 // essential for unions, where the operations performed by the assignment
4271 // operator cannot be represented as statements.
4272 //
4273 // Skip this for non-union classes with no fields; in that case, the defaulted
4274 // copy/move does not actually read the object.
4275 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4276 if (MD && MD->isDefaulted() &&
4277 (MD->getParent()->isUnion() ||
4278 (MD->isTrivial() && hasFields(MD->getParent())))) {
4279 assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4280, __extension__ __PRETTY_FUNCTION__))
4280 (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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4280, __extension__ __PRETTY_FUNCTION__))
;
4281 LValue RHS;
4282 RHS.setFrom(Info.Ctx, ArgValues[0]);
4283 APValue RHSValue;
4284 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4285 RHS, RHSValue))
4286 return false;
4287 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4288 RHSValue))
4289 return false;
4290 This->moveInto(Result);
4291 return true;
4292 } else if (MD && isLambdaCallOperator(MD)) {
4293 // We're in a lambda; determine the lambda capture field maps.
4294 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4295 Frame.LambdaThisCaptureField);
4296 }
4297
4298 StmtResult Ret = {Result, ResultSlot};
4299 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4300 if (ESR == ESR_Succeeded) {
4301 if (Callee->getReturnType()->isVoidType())
4302 return true;
4303 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4304 }
4305 return ESR == ESR_Returned;
4306}
4307
4308/// Evaluate a constructor call.
4309static bool HandleConstructorCall(const Expr *E, const LValue &This,
4310 APValue *ArgValues,
4311 const CXXConstructorDecl *Definition,
4312 EvalInfo &Info, APValue &Result) {
4313 SourceLocation CallLoc = E->getExprLoc();
4314 if (!Info.CheckCallLimit(CallLoc))
4315 return false;
4316
4317 const CXXRecordDecl *RD = Definition->getParent();
4318 if (RD->getNumVBases()) {
4319 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4320 return false;
4321 }
4322
4323 EvalInfo::EvaluatingConstructorRAII EvalObj(
4324 Info, {This.getLValueBase(), This.CallIndex});
4325 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4326
4327 // FIXME: Creating an APValue just to hold a nonexistent return value is
4328 // wasteful.
4329 APValue RetVal;
4330 StmtResult Ret = {RetVal, nullptr};
4331
4332 // If it's a delegating constructor, delegate.
4333 if (Definition->isDelegatingConstructor()) {
4334 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4335 {
4336 FullExpressionRAII InitScope(Info);
4337 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4338 return false;
4339 }
4340 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4341 }
4342
4343 // For a trivial copy or move constructor, perform an APValue copy. This is
4344 // essential for unions (or classes with anonymous union members), where the
4345 // operations performed by the constructor cannot be represented by
4346 // ctor-initializers.
4347 //
4348 // Skip this for empty non-union classes; we should not perform an
4349 // lvalue-to-rvalue conversion on them because their copy constructor does not
4350 // actually read them.
4351 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4352 (Definition->getParent()->isUnion() ||
4353 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4354 LValue RHS;
4355 RHS.setFrom(Info.Ctx, ArgValues[0]);
4356 return handleLValueToRValueConversion(
4357 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4358 RHS, Result);
4359 }
4360
4361 // Reserve space for the struct members.
4362 if (!RD->isUnion() && Result.isUninit())
4363 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4364 std::distance(RD->field_begin(), RD->field_end()));
4365
4366 if (RD->isInvalidDecl()) return false;
4367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4368
4369 // A scope for temporaries lifetime-extended by reference members.
4370 BlockScopeRAII LifetimeExtendedScope(Info);
4371
4372 bool Success = true;
4373 unsigned BasesSeen = 0;
4374#ifndef NDEBUG
4375 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4376#endif
4377 for (const auto *I : Definition->inits()) {
4378 LValue Subobject = This;
4379 APValue *Value = &Result;
4380
4381 // Determine the subobject to initialize.
4382 FieldDecl *FD = nullptr;
4383 if (I->isBaseInitializer()) {
4384 QualType BaseType(I->getBaseClass(), 0);
4385#ifndef NDEBUG
4386 // Non-virtual base classes are initialized in the order in the class
4387 // definition. We have already checked for virtual base classes.
4388 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4388, __extension__ __PRETTY_FUNCTION__))
;
4389 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4390, __extension__ __PRETTY_FUNCTION__))
4390 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4390, __extension__ __PRETTY_FUNCTION__))
;
4391 ++BaseIt;
4392#endif
4393 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4394 BaseType->getAsCXXRecordDecl(), &Layout))
4395 return false;
4396 Value = &Result.getStructBase(BasesSeen++);
4397 } else if ((FD = I->getMember())) {
4398 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4399 return false;
4400 if (RD->isUnion()) {
4401 Result = APValue(FD);
4402 Value = &Result.getUnionValue();
4403 } else {
4404 Value = &Result.getStructField(FD->getFieldIndex());
4405 }
4406 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4407 // Walk the indirect field decl's chain to find the object to initialize,
4408 // and make sure we've initialized every step along it.
4409 for (auto *C : IFD->chain()) {
4410 FD = cast<FieldDecl>(C);
4411 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4412 // Switch the union field if it differs. This happens if we had
4413 // preceding zero-initialization, and we're now initializing a union
4414 // subobject other than the first.
4415 // FIXME: In this case, the values of the other subobjects are
4416 // specified, since zero-initialization sets all padding bits to zero.
4417 if (Value->isUninit() ||
4418 (Value->isUnion() && Value->getUnionField() != FD)) {
4419 if (CD->isUnion())
4420 *Value = APValue(FD);
4421 else
4422 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4423 std::distance(CD->field_begin(), CD->field_end()));
4424 }
4425 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4426 return false;
4427 if (CD->isUnion())
4428 Value = &Value->getUnionValue();
4429 else
4430 Value = &Value->getStructField(FD->getFieldIndex());
4431 }
4432 } else {
4433 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4433)
;
4434 }
4435
4436 FullExpressionRAII InitScope(Info);
4437 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4438 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4439 *Value, FD))) {
4440 // If we're checking for a potential constant expression, evaluate all
4441 // initializers even if some of them fail.
4442 if (!Info.noteFailure())
4443 return false;
4444 Success = false;
4445 }
4446 }
4447
4448 return Success &&
4449 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4450}
4451
4452static bool HandleConstructorCall(const Expr *E, const LValue &This,
4453 ArrayRef<const Expr*> Args,
4454 const CXXConstructorDecl *Definition,
4455 EvalInfo &Info, APValue &Result) {
4456 ArgVector ArgValues(Args.size());
4457 if (!EvaluateArgs(Args, ArgValues, Info))
4458 return false;
4459
4460 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4461 Info, Result);
4462}
4463
4464//===----------------------------------------------------------------------===//
4465// Generic Evaluation
4466//===----------------------------------------------------------------------===//
4467namespace {
4468
4469template <class Derived>
4470class ExprEvaluatorBase
4471 : public ConstStmtVisitor<Derived, bool> {
4472private:
4473 Derived &getDerived() { return static_cast<Derived&>(*this); }
4474 bool DerivedSuccess(const APValue &V, const Expr *E) {
4475 return getDerived().Success(V, E);
4476 }
4477 bool DerivedZeroInitialization(const Expr *E) {
4478 return getDerived().ZeroInitialization(E);
4479 }
4480
4481 // Check whether a conditional operator with a non-constant condition is a
4482 // potential constant expression. If neither arm is a potential constant
4483 // expression, then the conditional operator is not either.
4484 template<typename ConditionalOperator>
4485 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4486 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4486, __extension__ __PRETTY_FUNCTION__))
;
4487
4488 // Speculatively evaluate both arms.
4489 SmallVector<PartialDiagnosticAt, 8> Diag;
4490 {
4491 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4492 StmtVisitorTy::Visit(E->getFalseExpr());
4493 if (Diag.empty())
4494 return;
4495 }
4496
4497 {
4498 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4499 Diag.clear();
4500 StmtVisitorTy::Visit(E->getTrueExpr());
4501 if (Diag.empty())
4502 return;
4503 }
4504
4505 Error(E, diag::note_constexpr_conditional_never_const);
4506 }
4507
4508
4509 template<typename ConditionalOperator>
4510 bool HandleConditionalOperator(const ConditionalOperator *E) {
4511 bool BoolResult;
4512 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4513 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4514 CheckPotentialConstantConditional(E);
4515 return false;
4516 }
4517 if (Info.noteFailure()) {
4518 StmtVisitorTy::Visit(E->getTrueExpr());
4519 StmtVisitorTy::Visit(E->getFalseExpr());
4520 }
4521 return false;
4522 }
4523
4524 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4525 return StmtVisitorTy::Visit(EvalExpr);
4526 }
4527
4528protected:
4529 EvalInfo &Info;
4530 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4531 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4532
4533 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4534 return Info.CCEDiag(E, D);
4535 }
4536
4537 bool ZeroInitialization(const Expr *E) { return Error(E); }
4538
4539public:
4540 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4541
4542 EvalInfo &getEvalInfo() { return Info; }
4543
4544 /// Report an evaluation error. This should only be called when an error is
4545 /// first discovered. When propagating an error, just return false.
4546 bool Error(const Expr *E, diag::kind D) {
4547 Info.FFDiag(E, D);
4548 return false;
4549 }
4550 bool Error(const Expr *E) {
4551 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4552 }
4553
4554 bool VisitStmt(const Stmt *) {
4555 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4555)
;
4556 }
4557 bool VisitExpr(const Expr *E) {
4558 return Error(E);
4559 }
4560
4561 bool VisitParenExpr(const ParenExpr *E)
4562 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4563 bool VisitUnaryExtension(const UnaryOperator *E)
4564 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4565 bool VisitUnaryPlus(const UnaryOperator *E)
4566 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4567 bool VisitChooseExpr(const ChooseExpr *E)
4568 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4569 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4570 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4571 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4572 { return StmtVisitorTy::Visit(E->getReplacement()); }
4573 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4574 { return StmtVisitorTy::Visit(E->getExpr()); }
4575 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4576 // The initializer may not have been parsed yet, or might be erroneous.
4577 if (!E->getExpr())
4578 return Error(E);
4579 return StmtVisitorTy::Visit(E->getExpr());
4580 }
4581 // We cannot create any objects for which cleanups are required, so there is
4582 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4583 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4584 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4585
4586 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4587 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4588 return static_cast<Derived*>(this)->VisitCastExpr(E);
4589 }
4590 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4591 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4592 return static_cast<Derived*>(this)->VisitCastExpr(E);
4593 }
4594
4595 bool VisitBinaryOperator(const BinaryOperator *E) {
4596 switch (E->getOpcode()) {
4597 default:
4598 return Error(E);
4599
4600 case BO_Comma:
4601 VisitIgnoredValue(E->getLHS());
4602 return StmtVisitorTy::Visit(E->getRHS());
4603
4604 case BO_PtrMemD:
4605 case BO_PtrMemI: {
4606 LValue Obj;
4607 if (!HandleMemberPointerAccess(Info, E, Obj))
4608 return false;
4609 APValue Result;
4610 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4611 return false;
4612 return DerivedSuccess(Result, E);
4613 }
4614 }
4615 }
4616
4617 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4618 // Evaluate and cache the common expression. We treat it as a temporary,
4619 // even though it's not quite the same thing.
4620 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4621 Info, E->getCommon()))
4622 return false;
4623
4624 return HandleConditionalOperator(E);
4625 }
4626
4627 bool VisitConditionalOperator(const ConditionalOperator *E) {
4628 bool IsBcpCall = false;
4629 // If the condition (ignoring parens) is a __builtin_constant_p call,
4630 // the result is a constant expression if it can be folded without
4631 // side-effects. This is an important GNU extension. See GCC PR38377
4632 // for discussion.
4633 if (const CallExpr *CallCE =
4634 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4635 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4636 IsBcpCall = true;
4637
4638 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4639 // constant expression; we can't check whether it's potentially foldable.
4640 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4641 return false;
4642
4643 FoldConstant Fold(Info, IsBcpCall);
4644 if (!HandleConditionalOperator(E)) {
4645 Fold.keepDiagnostics();
4646 return false;
4647 }
4648
4649 return true;
4650 }
4651
4652 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4653 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4654 return DerivedSuccess(*Value, E);
4655
4656 const Expr *Source = E->getSourceExpr();
4657 if (!Source)
4658 return Error(E);
4659 if (Source == E) { // sanity checking.
4660 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4660, __extension__ __PRETTY_FUNCTION__))
;
4661 return Error(E);
4662 }
4663 return StmtVisitorTy::Visit(Source);
4664 }
4665
4666 bool VisitCallExpr(const CallExpr *E) {
4667 APValue Result;
4668 if (!handleCallExpr(E, Result, nullptr))
4669 return false;
4670 return DerivedSuccess(Result, E);
4671 }
4672
4673 bool handleCallExpr(const CallExpr *E, APValue &Result,
4674 const LValue *ResultSlot) {
4675 const Expr *Callee = E->getCallee()->IgnoreParens();
4676 QualType CalleeType = Callee->getType();
4677
4678 const FunctionDecl *FD = nullptr;
4679 LValue *This = nullptr, ThisVal;
4680 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4681 bool HasQualifier = false;
4682
4683 // Extract function decl and 'this' pointer from the callee.
4684 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4685 const ValueDecl *Member = nullptr;
4686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4687 // Explicit bound member calls, such as x.f() or p->g();
4688 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4689 return false;
4690 Member = ME->getMemberDecl();
4691 This = &ThisVal;
4692 HasQualifier = ME->hasQualifier();
4693 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4694 // Indirect bound member calls ('.*' or '->*').
4695 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4696 if (!Member) return false;
4697 This = &ThisVal;
4698 } else
4699 return Error(Callee);
4700
4701 FD = dyn_cast<FunctionDecl>(Member);
4702 if (!FD)
4703 return Error(Callee);
4704 } else if (CalleeType->isFunctionPointerType()) {
4705 LValue Call;
4706 if (!EvaluatePointer(Callee, Call, Info))
4707 return false;
4708
4709 if (!Call.getLValueOffset().isZero())
4710 return Error(Callee);
4711 FD = dyn_cast_or_null<FunctionDecl>(
4712 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4713 if (!FD)
4714 return Error(Callee);
4715 // Don't call function pointers which have been cast to some other type.
4716 // Per DR (no number yet), the caller and callee can differ in noexcept.
4717 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4718 CalleeType->getPointeeType(), FD->getType())) {
4719 return Error(E);
4720 }
4721
4722 // Overloaded operator calls to member functions are represented as normal
4723 // calls with '*this' as the first argument.
4724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4725 if (MD && !MD->isStatic()) {
4726 // FIXME: When selecting an implicit conversion for an overloaded
4727 // operator delete, we sometimes try to evaluate calls to conversion
4728 // operators without a 'this' parameter!
4729 if (Args.empty())
4730 return Error(E);
4731
4732 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4733 return false;
4734 This = &ThisVal;
4735 Args = Args.slice(1);
4736 } else if (MD && MD->isLambdaStaticInvoker()) {
4737 // Map the static invoker for the lambda back to the call operator.
4738 // Conveniently, we don't have to slice out the 'this' argument (as is
4739 // being done for the non-static case), since a static member function
4740 // doesn't have an implicit argument passed in.
4741 const CXXRecordDecl *ClosureClass = MD->getParent();
4742 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4744, __extension__ __PRETTY_FUNCTION__))
4743 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4744, __extension__ __PRETTY_FUNCTION__))
4744 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4744, __extension__ __PRETTY_FUNCTION__))
;
4745
4746 const CXXMethodDecl *LambdaCallOp =
4747 ClosureClass->getLambdaCallOperator();
4748
4749 // Set 'FD', the function that will be called below, to the call
4750 // operator. If the closure object represents a generic lambda, find
4751 // the corresponding specialization of the call operator.
4752
4753 if (ClosureClass->isGenericLambda()) {
4754 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4756, __extension__ __PRETTY_FUNCTION__))
4755 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4756, __extension__ __PRETTY_FUNCTION__))
4756 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4756, __extension__ __PRETTY_FUNCTION__))
;
4757 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4758 FunctionTemplateDecl *CallOpTemplate =
4759 LambdaCallOp->getDescribedFunctionTemplate();
4760 void *InsertPos = nullptr;
4761 FunctionDecl *CorrespondingCallOpSpecialization =
4762 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4763 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4765, __extension__ __PRETTY_FUNCTION__))
4764 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4765, __extension__ __PRETTY_FUNCTION__))
4765 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4765, __extension__ __PRETTY_FUNCTION__))
;
4766 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4767 } else
4768 FD = LambdaCallOp;
4769 }
4770
4771
4772 } else
4773 return Error(E);
4774
4775 if (This && !This->checkSubobject(Info, E, CSK_This))
4776 return false;
4777
4778 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4779 // calls to such functions in constant expressions.
4780 if (This && !HasQualifier &&
4781 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4782 return Error(E, diag::note_constexpr_virtual_call);
4783
4784 const FunctionDecl *Definition = nullptr;
4785 Stmt *Body = FD->getBody(Definition);
4786
4787 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4788 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4789 Result, ResultSlot))
4790 return false;
4791
4792 return true;
4793 }
4794
4795 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4796 return StmtVisitorTy::Visit(E->getInitializer());
4797 }
4798 bool VisitInitListExpr(const InitListExpr *E) {
4799 if (E->getNumInits() == 0)
4800 return DerivedZeroInitialization(E);
4801 if (E->getNumInits() == 1)
4802 return StmtVisitorTy::Visit(E->getInit(0));
4803 return Error(E);
4804 }
4805 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4806 return DerivedZeroInitialization(E);
4807 }
4808 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4809 return DerivedZeroInitialization(E);
4810 }
4811 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4812 return DerivedZeroInitialization(E);
4813 }
4814
4815 /// A member expression where the object is a prvalue is itself a prvalue.
4816 bool VisitMemberExpr(const MemberExpr *E) {
4817 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4817, __extension__ __PRETTY_FUNCTION__))
;
4818
4819 APValue Val;
4820 if (!Evaluate(Val, Info, E->getBase()))
4821 return false;
4822
4823 QualType BaseTy = E->getBase()->getType();
4824
4825 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4826 if (!FD) return Error(E);
4827 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4827, __extension__ __PRETTY_FUNCTION__))
;
4828 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4829, __extension__ __PRETTY_FUNCTION__))
4829 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4829, __extension__ __PRETTY_FUNCTION__))
;
4830
4831 CompleteObject Obj(&Val, BaseTy);
4832 SubobjectDesignator Designator(BaseTy);
4833 Designator.addDeclUnchecked(FD);
4834
4835 APValue Result;
4836 return extractSubobject(Info, E, Obj, Designator, Result) &&
4837 DerivedSuccess(Result, E);
4838 }
4839
4840 bool VisitCastExpr(const CastExpr *E) {
4841 switch (E->getCastKind()) {
4842 default:
4843 break;
4844
4845 case CK_AtomicToNonAtomic: {
4846 APValue AtomicVal;
4847 // This does not need to be done in place even for class/array types:
4848 // atomic-to-non-atomic conversion implies copying the object
4849 // representation.
4850 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4851 return false;
4852 return DerivedSuccess(AtomicVal, E);
4853 }
4854
4855 case CK_NoOp:
4856 case CK_UserDefinedConversion:
4857 return StmtVisitorTy::Visit(E->getSubExpr());
4858
4859 case CK_LValueToRValue: {
4860 LValue LVal;
4861 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4862 return false;
4863 APValue RVal;
4864 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4865 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4866 LVal, RVal))
4867 return false;
4868 return DerivedSuccess(RVal, E);
4869 }
4870 }
4871
4872 return Error(E);
4873 }
4874
4875 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4876 return VisitUnaryPostIncDec(UO);
4877 }
4878 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4879 return VisitUnaryPostIncDec(UO);
4880 }
4881 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4883 return Error(UO);
4884
4885 LValue LVal;
4886 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4887 return false;
4888 APValue RVal;
4889 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4890 UO->isIncrementOp(), &RVal))
4891 return false;
4892 return DerivedSuccess(RVal, UO);
4893 }
4894
4895 bool VisitStmtExpr(const StmtExpr *E) {
4896 // We will have checked the full-expressions inside the statement expression
4897 // when they were completed, and don't need to check them again now.
4898 if (Info.checkingForOverflow())
4899 return Error(E);
4900
4901 BlockScopeRAII Scope(Info);
4902 const CompoundStmt *CS = E->getSubStmt();
4903 if (CS->body_empty())
4904 return true;
4905
4906 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4907 BE = CS->body_end();
4908 /**/; ++BI) {
4909 if (BI + 1 == BE) {
4910 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4911 if (!FinalExpr) {
4912 Info.FFDiag((*BI)->getLocStart(),
4913 diag::note_constexpr_stmt_expr_unsupported);
4914 return false;
4915 }
4916 return this->Visit(FinalExpr);
4917 }
4918
4919 APValue ReturnValue;
4920 StmtResult Result = { ReturnValue, nullptr };
4921 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4922 if (ESR != ESR_Succeeded) {
4923 // FIXME: If the statement-expression terminated due to 'return',
4924 // 'break', or 'continue', it would be nice to propagate that to
4925 // the outer statement evaluation rather than bailing out.
4926 if (ESR != ESR_Failed)
4927 Info.FFDiag((*BI)->getLocStart(),
4928 diag::note_constexpr_stmt_expr_unsupported);
4929 return false;
4930 }
4931 }
4932
4933 llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above."
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4933)
;
4934 }
4935
4936 /// Visit a value which is evaluated, but whose value is ignored.
4937 void VisitIgnoredValue(const Expr *E) {
4938 EvaluateIgnoredValue(Info, E);
4939 }
4940
4941 /// Potentially visit a MemberExpr's base expression.
4942 void VisitIgnoredBaseExpression(const Expr *E) {
4943 // While MSVC doesn't evaluate the base expression, it does diagnose the
4944 // presence of side-effecting behavior.
4945 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4946 return;
4947 VisitIgnoredValue(E);
4948 }
4949};
4950
4951}
4952
4953//===----------------------------------------------------------------------===//
4954// Common base class for lvalue and temporary evaluation.
4955//===----------------------------------------------------------------------===//
4956namespace {
4957template<class Derived>
4958class LValueExprEvaluatorBase
4959 : public ExprEvaluatorBase<Derived> {
4960protected:
4961 LValue &Result;
4962 bool InvalidBaseOK;
4963 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4964 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4965
4966 bool Success(APValue::LValueBase B) {
4967 Result.set(B);
4968 return true;
4969 }
4970
4971 bool evaluatePointer(const Expr *E, LValue &Result) {
4972 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4973 }
4974
4975public:
4976 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4977 : ExprEvaluatorBaseTy(Info), Result(Result),
4978 InvalidBaseOK(InvalidBaseOK) {}
4979
4980 bool Success(const APValue &V, const Expr *E) {
4981 Result.setFrom(this->Info.Ctx, V);
4982 return true;
4983 }
4984
4985 bool VisitMemberExpr(const MemberExpr *E) {
4986 // Handle non-static data members.
4987 QualType BaseTy;
4988 bool EvalOK;
4989 if (E->isArrow()) {
4990 EvalOK = evaluatePointer(E->getBase(), Result);
4991 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4992 } else if (E->getBase()->isRValue()) {
4993 assert(E->getBase()->getType()->isRecordType())(static_cast <bool> (E->getBase()->getType()->
isRecordType()) ? void (0) : __assert_fail ("E->getBase()->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 4993, __extension__ __PRETTY_FUNCTION__))
;
4994 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4995 BaseTy = E->getBase()->getType();
4996 } else {
4997 EvalOK = this->Visit(E->getBase());
4998 BaseTy = E->getBase()->getType();
4999 }
5000 if (!EvalOK) {
5001 if (!InvalidBaseOK)
5002 return false;
5003 Result.setInvalid(E);
5004 return true;
5005 }
5006
5007 const ValueDecl *MD = E->getMemberDecl();
5008 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5009 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5010, __extension__ __PRETTY_FUNCTION__))
5010 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5010, __extension__ __PRETTY_FUNCTION__))
;
5011 (void)BaseTy;
5012 if (!HandleLValueMember(this->Info, E, Result, FD))
5013 return false;
5014 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5015 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5016 return false;
5017 } else
5018 return this->Error(E);
5019
5020 if (MD->getType()->isReferenceType()) {
5021 APValue RefValue;
5022 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5023 RefValue))
5024 return false;
5025 return Success(RefValue, E);
5026 }
5027 return true;
5028 }
5029
5030 bool VisitBinaryOperator(const BinaryOperator *E) {
5031 switch (E->getOpcode()) {
5032 default:
5033 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5034
5035 case BO_PtrMemD:
5036 case BO_PtrMemI:
5037 return HandleMemberPointerAccess(this->Info, E, Result);
5038 }
5039 }
5040
5041 bool VisitCastExpr(const CastExpr *E) {
5042 switch (E->getCastKind()) {
5043 default:
5044 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5045
5046 case CK_DerivedToBase:
5047 case CK_UncheckedDerivedToBase:
5048 if (!this->Visit(E->getSubExpr()))
5049 return false;
5050
5051 // Now figure out the necessary offset to add to the base LV to get from
5052 // the derived class to the base class.
5053 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5054 Result);
5055 }
5056 }
5057};
5058}
5059
5060//===----------------------------------------------------------------------===//
5061// LValue Evaluation
5062//
5063// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5064// function designators (in C), decl references to void objects (in C), and
5065// temporaries (if building with -Wno-address-of-temporary).
5066//
5067// LValue evaluation produces values comprising a base expression of one of the
5068// following types:
5069// - Declarations
5070// * VarDecl
5071// * FunctionDecl
5072// - Literals
5073// * CompoundLiteralExpr in C (and in global scope in C++)
5074// * StringLiteral
5075// * CXXTypeidExpr
5076// * PredefinedExpr
5077// * ObjCStringLiteralExpr
5078// * ObjCEncodeExpr
5079// * AddrLabelExpr
5080// * BlockExpr
5081// * CallExpr for a MakeStringConstant builtin
5082// - Locals and temporaries
5083// * MaterializeTemporaryExpr
5084// * Any Expr, with a CallIndex indicating the function in which the temporary
5085// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5086// from the AST (FIXME).
5087// * A MaterializeTemporaryExpr that has static storage duration, with no
5088// CallIndex, for a lifetime-extended temporary.
5089// plus an offset in bytes.
5090//===----------------------------------------------------------------------===//
5091namespace {
5092class LValueExprEvaluator
5093 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5094public:
5095 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5096 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5097
5098 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5099 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5100
5101 bool VisitDeclRefExpr(const DeclRefExpr *E);
5102 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5103 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5104 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5105 bool VisitMemberExpr(const MemberExpr *E);
5106 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5107 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5108 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5109 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5110 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5111 bool VisitUnaryDeref(const UnaryOperator *E);
5112 bool VisitUnaryReal(const UnaryOperator *E);
5113 bool VisitUnaryImag(const UnaryOperator *E);
5114 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5115 return VisitUnaryPreIncDec(UO);
5116 }
5117 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5118 return VisitUnaryPreIncDec(UO);
5119 }
5120 bool VisitBinAssign(const BinaryOperator *BO);
5121 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5122
5123 bool VisitCastExpr(const CastExpr *E) {
5124 switch (E->getCastKind()) {
5125 default:
5126 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5127
5128 case CK_LValueBitCast:
5129 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5130 if (!Visit(E->getSubExpr()))
5131 return false;
5132 Result.Designator.setInvalid();
5133 return true;
5134
5135 case CK_BaseToDerived:
5136 if (!Visit(E->getSubExpr()))
5137 return false;
5138 return HandleBaseToDerivedCast(Info, E, Result);
5139 }
5140 }
5141};
5142} // end anonymous namespace
5143
5144/// Evaluate an expression as an lvalue. This can be legitimately called on
5145/// expressions which are not glvalues, in three cases:
5146/// * function designators in C, and
5147/// * "extern void" objects
5148/// * @selector() expressions in Objective-C
5149static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5150 bool InvalidBaseOK) {
5151 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5152, __extension__ __PRETTY_FUNCTION__))
5152 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5152, __extension__ __PRETTY_FUNCTION__))
;
5153 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5154}
5155
5156bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5158 return Success(FD);
5159 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5160 return VisitVarDecl(E, VD);
5161 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5162 return Visit(BD->getBinding());
5163 return Error(E);
5164}
5165
5166
5167bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5168
5169 // If we are within a lambda's call operator, check whether the 'VD' referred
5170 // to within 'E' actually represents a lambda-capture that maps to a
5171 // data-member/field within the closure object, and if so, evaluate to the
5172 // field or what the field refers to.
5173 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5174 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5175 if (Info.checkingPotentialConstantExpression())
5176 return false;
5177 // Start with 'Result' referring to the complete closure object...
5178 Result = *Info.CurrentCall->This;
5179 // ... then update it to refer to the field of the closure object
5180 // that represents the capture.
5181 if (!HandleLValueMember(Info, E, Result, FD))
5182 return false;
5183 // And if the field is of reference type, update 'Result' to refer to what
5184 // the field refers to.
5185 if (FD->getType()->isReferenceType()) {
5186 APValue RVal;
5187 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5188 RVal))
5189 return false;
5190 Result.setFrom(Info.Ctx, RVal);
5191 }
5192 return true;
5193 }
5194 }
5195 CallStackFrame *Frame = nullptr;
5196 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5197 // Only if a local variable was declared in the function currently being
5198 // evaluated, do we expect to be able to find its value in the current
5199 // frame. (Otherwise it was likely declared in an enclosing context and
5200 // could either have a valid evaluatable value (for e.g. a constexpr
5201 // variable) or be ill-formed (and trigger an appropriate evaluation
5202 // diagnostic)).
5203 if (Info.CurrentCall->Callee &&
5204 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5205 Frame = Info.CurrentCall;
5206 }
5207 }
5208
5209 if (!VD->getType()->isReferenceType()) {
5210 if (Frame) {
5211 Result.set(VD, Frame->Index);
5212 return true;
5213 }
5214 return Success(VD);
5215 }
5216
5217 APValue *V;
5218 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5219 return false;
5220 if (V->isUninit()) {
5221 if (!Info.checkingPotentialConstantExpression())
5222 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5223 return false;
5224 }
5225 return Success(*V, E);
5226}
5227
5228bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5229 const MaterializeTemporaryExpr *E) {
5230 // Walk through the expression to find the materialized temporary itself.
5231 SmallVector<const Expr *, 2> CommaLHSs;
5232 SmallVector<SubobjectAdjustment, 2> Adjustments;
5233 const Expr *Inner = E->GetTemporaryExpr()->
5234 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5235
5236 // If we passed any comma operators, evaluate their LHSs.
5237 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5238 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5239 return false;
5240
5241 // A materialized temporary with static storage duration can appear within the
5242 // result of a constant expression evaluation, so we need to preserve its
5243 // value for use outside this evaluation.
5244 APValue *Value;
5245 if (E->getStorageDuration() == SD_Static) {
5246 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5247 *Value = APValue();
5248 Result.set(E);
5249 } else {
5250 Value = &Info.CurrentCall->
5251 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5252 Result.set(E, Info.CurrentCall->Index);
5253 }
5254
5255 QualType Type = Inner->getType();
5256
5257 // Materialize the temporary itself.
5258 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5259 (E->getStorageDuration() == SD_Static &&
5260 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5261 *Value = APValue();
5262 return false;
5263 }
5264
5265 // Adjust our lvalue to refer to the desired subobject.
5266 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5267 --I;
5268 switch (Adjustments[I].Kind) {
5269 case SubobjectAdjustment::DerivedToBaseAdjustment:
5270 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5271 Type, Result))
5272 return false;
5273 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5274 break;
5275
5276 case SubobjectAdjustment::FieldAdjustment:
5277 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5278 return false;
5279 Type = Adjustments[I].Field->getType();
5280 break;
5281
5282 case SubobjectAdjustment::MemberPointerAdjustment:
5283 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5284 Adjustments[I].Ptr.RHS))
5285 return false;
5286 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5287 break;
5288 }
5289 }
5290
5291 return true;
5292}
5293
5294bool
5295LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5296 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5297, __extension__ __PRETTY_FUNCTION__))
5297 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5297, __extension__ __PRETTY_FUNCTION__))
;
5298 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5299 // only see this when folding in C, so there's no standard to follow here.
5300 return Success(E);
5301}
5302
5303bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5304 if (!E->isPotentiallyEvaluated())
5305 return Success(E);
5306
5307 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5308 << E->getExprOperand()->getType()
5309 << E->getExprOperand()->getSourceRange();
5310 return false;
5311}
5312
5313bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5314 return Success(E);
5315}
5316
5317bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5318 // Handle static data members.
5319 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5320 VisitIgnoredBaseExpression(E->getBase());
5321 return VisitVarDecl(E, VD);
5322 }
5323
5324 // Handle static member functions.
5325 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5326 if (MD->isStatic()) {
5327 VisitIgnoredBaseExpression(E->getBase());
5328 return Success(MD);
5329 }
5330 }
5331
5332 // Handle non-static data members.
5333 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5334}
5335
5336bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5337 // FIXME: Deal with vectors as array subscript bases.
5338 if (E->getBase()->getType()->isVectorType())
5339 return Error(E);
5340
5341 bool Success = true;
5342 if (!evaluatePointer(E->getBase(), Result)) {
5343 if (!Info.noteFailure())
5344 return false;
5345 Success = false;
5346 }
5347
5348 APSInt Index;
5349 if (!EvaluateInteger(E->getIdx(), Index, Info))
5350 return false;
5351
5352 return Success &&
5353 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5354}
5355
5356bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5357 return evaluatePointer(E->getSubExpr(), Result);
5358}
5359
5360bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5361 if (!Visit(E->getSubExpr()))
5362 return false;
5363 // __real is a no-op on scalar lvalues.
5364 if (E->getSubExpr()->getType()->isAnyComplexType())
5365 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5366 return true;
5367}
5368
5369bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5370 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5371, __extension__ __PRETTY_FUNCTION__))
5371 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5371, __extension__ __PRETTY_FUNCTION__))
;
5372 if (!Visit(E->getSubExpr()))
5373 return false;
5374 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5375 return true;
5376}
5377
5378bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5379 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5380 return Error(UO);
5381
5382 if (!this->Visit(UO->getSubExpr()))
5383 return false;
5384
5385 return handleIncDec(
5386 this->Info, UO, Result, UO->getSubExpr()->getType(),
5387 UO->isIncrementOp(), nullptr);
5388}
5389
5390bool LValueExprEvaluator::VisitCompoundAssignOperator(
5391 const CompoundAssignOperator *CAO) {
5392 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5393 return Error(CAO);
5394
5395 APValue RHS;
5396
5397 // The overall lvalue result is the result of evaluating the LHS.
5398 if (!this->Visit(CAO->getLHS())) {
5399 if (Info.noteFailure())
5400 Evaluate(RHS, this->Info, CAO->getRHS());
5401 return false;
5402 }
5403
5404 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5405 return false;
5406
5407 return handleCompoundAssignment(
5408 this->Info, CAO,
5409 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5410 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5411}
5412
5413bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5415 return Error(E);
5416
5417 APValue NewVal;
5418
5419 if (!this->Visit(E->getLHS())) {
5420 if (Info.noteFailure())
5421 Evaluate(NewVal, this->Info, E->getRHS());
5422 return false;
5423 }
5424
5425 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5426 return false;
5427
5428 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5429 NewVal);
5430}
5431
5432//===----------------------------------------------------------------------===//
5433// Pointer Evaluation
5434//===----------------------------------------------------------------------===//
5435
5436/// \brief Attempts to compute the number of bytes available at the pointer
5437/// returned by a function with the alloc_size attribute. Returns true if we
5438/// were successful. Places an unsigned number into `Result`.
5439///
5440/// This expects the given CallExpr to be a call to a function with an
5441/// alloc_size attribute.
5442static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5443 const CallExpr *Call,
5444 llvm::APInt &Result) {
5445 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5446
5447 // alloc_size args are 1-indexed, 0 means not present.
5448 assert(AllocSize && AllocSize->getElemSizeParam() != 0)(static_cast <bool> (AllocSize && AllocSize->
getElemSizeParam() != 0) ? void (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam() != 0"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5448, __extension__ __PRETTY_FUNCTION__))
;
5449 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5450 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5451 if (Call->getNumArgs() <= SizeArgNo)
5452 return false;
5453
5454 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5455 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5456 return false;
5457 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5458 return false;
5459 Into = Into.zextOrSelf(BitsInSizeT);
5460 return true;
5461 };
5462
5463 APSInt SizeOfElem;
5464 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5465 return false;
5466
5467 if (!AllocSize->getNumElemsParam()) {
5468 Result = std::move(SizeOfElem);
5469 return true;
5470 }
5471
5472 APSInt NumberOfElems;
5473 // Argument numbers start at 1
5474 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5475 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5476 return false;
5477
5478 bool Overflow;
5479 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5480 if (Overflow)
5481 return false;
5482
5483 Result = std::move(BytesAvailable);
5484 return true;
5485}
5486
5487/// \brief Convenience function. LVal's base must be a call to an alloc_size
5488/// function.
5489static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5490 const LValue &LVal,
5491 llvm::APInt &Result) {
5492 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5493, __extension__ __PRETTY_FUNCTION__))
5493 "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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5493, __extension__ __PRETTY_FUNCTION__))
;
5494 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5495 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5496 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5497}
5498
5499/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5500/// a function with the alloc_size attribute. If it was possible to do so, this
5501/// function will return true, make Result's Base point to said function call,
5502/// and mark Result's Base as invalid.
5503static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5504 LValue &Result) {
5505 if (Base.isNull())
5506 return false;
5507
5508 // Because we do no form of static analysis, we only support const variables.
5509 //
5510 // Additionally, we can't support parameters, nor can we support static
5511 // variables (in the latter case, use-before-assign isn't UB; in the former,
5512 // we have no clue what they'll be assigned to).
5513 const auto *VD =
5514 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5515 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5516 return false;
5517
5518 const Expr *Init = VD->getAnyInitializer();
5519 if (!Init)
5520 return false;
5521
5522 const Expr *E = Init->IgnoreParens();
5523 if (!tryUnwrapAllocSizeCall(E))
5524 return false;
5525
5526 // Store E instead of E unwrapped so that the type of the LValue's base is
5527 // what the user wanted.
5528 Result.setInvalid(E);
5529
5530 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5531 Result.addUnsizedArray(Info, E, Pointee);
5532 return true;
5533}
5534
5535namespace {
5536class PointerExprEvaluator
5537 : public ExprEvaluatorBase<PointerExprEvaluator> {
5538 LValue &Result;
5539 bool InvalidBaseOK;
5540
5541 bool Success(const Expr *E) {
5542 Result.set(E);
5543 return true;
5544 }
5545
5546 bool evaluateLValue(const Expr *E, LValue &Result) {
5547 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5548 }
5549
5550 bool evaluatePointer(const Expr *E, LValue &Result) {
5551 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5552 }
5553
5554 bool visitNonBuiltinCallExpr(const CallExpr *E);
5555public:
5556
5557 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5558 : ExprEvaluatorBaseTy(info), Result(Result),
5559 InvalidBaseOK(InvalidBaseOK) {}
5560
5561 bool Success(const APValue &V, const Expr *E) {
5562 Result.setFrom(Info.Ctx, V);
5563 return true;
5564 }
5565 bool ZeroInitialization(const Expr *E) {
5566 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5567 Result.setNull(E->getType(), TargetVal);
5568 return true;
5569 }
5570
5571 bool VisitBinaryOperator(const BinaryOperator *E);
5572 bool VisitCastExpr(const CastExpr* E);
5573 bool VisitUnaryAddrOf(const UnaryOperator *E);
5574 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5575 { return Success(E); }
5576 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5577 if (Info.noteFailure())
5578 EvaluateIgnoredValue(Info, E->getSubExpr());
5579 return Error(E);
5580 }
5581 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5582 { return Success(E); }
5583 bool VisitCallExpr(const CallExpr *E);
5584 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5585 bool VisitBlockExpr(const BlockExpr *E) {
5586 if (!E->getBlockDecl()->hasCaptures())
5587 return Success(E);
5588 return Error(E);
5589 }
5590 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5591 // Can't look at 'this' when checking a potential constant expression.
5592 if (Info.checkingPotentialConstantExpression())
5593 return false;
5594 if (!Info.CurrentCall->This) {
5595 if (Info.getLangOpts().CPlusPlus11)
5596 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5597 else
5598 Info.FFDiag(E);
5599 return false;
5600 }
5601 Result = *Info.CurrentCall->This;
5602 // If we are inside a lambda's call operator, the 'this' expression refers
5603 // to the enclosing '*this' object (either by value or reference) which is
5604 // either copied into the closure object's field that represents the '*this'
5605 // or refers to '*this'.
5606 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5607 // Update 'Result' to refer to the data member/field of the closure object
5608 // that represents the '*this' capture.
5609 if (!HandleLValueMember(Info, E, Result,
5610 Info.CurrentCall->LambdaThisCaptureField))
5611 return false;
5612 // If we captured '*this' by reference, replace the field with its referent.
5613 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5614 ->isPointerType()) {
5615 APValue RVal;
5616 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5617 RVal))
5618 return false;
5619
5620 Result.setFrom(Info.Ctx, RVal);
5621 }
5622 }
5623 return true;
5624 }
5625
5626 // FIXME: Missing: @protocol, @selector
5627};
5628} // end anonymous namespace
5629
5630static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5631 bool InvalidBaseOK) {
5632 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 5632, __extension__ __PRETTY_FUNCTION__))
;
5633 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5634}
5635
5636bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5637 if (E->getOpcode() != BO_Add &&
5638 E->getOpcode() != BO_Sub)
5639 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5640
5641 const Expr *PExp = E->getLHS();
5642 const Expr *IExp = E->getRHS();
5643 if (IExp->getType()->isPointerType())
5644 std::swap(PExp, IExp);
5645
5646 bool EvalPtrOK = evaluatePointer(PExp, Result);
5647 if (!EvalPtrOK && !Info.noteFailure())
5648 return false;
5649
5650 llvm::APSInt Offset;
5651 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5652 return false;
5653
5654 if (E->getOpcode() == BO_Sub)
5655 negateAsSigned(Offset);
5656
5657 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5658 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5659}
5660
5661bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5662 return evaluateLValue(E->getSubExpr(), Result);
5663}
5664
5665bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5666 const Expr* SubExpr = E->getSubExpr();
5667
5668 switch (E->getCastKind()) {
5669 default:
5670 break;
5671
5672 case CK_BitCast:
5673 case CK_CPointerToObjCPointerCast:
5674 case CK_BlockPointerToObjCPointerCast:
5675 case CK_AnyPointerToBlockPointerCast:
5676 case CK_AddressSpaceConversion:
5677 if (!Visit(SubExpr))
5678 return false;
5679 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5680 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5681 // also static_casts, but we disallow them as a resolution to DR1312.
5682 if (!E->getType()->isVoidPointerType()) {
5683 Result.Designator.setInvalid();
5684 if (SubExpr->getType()->isVoidPointerType())
5685 CCEDiag(E, diag::note_constexpr_invalid_cast)
5686 << 3 << SubExpr->getType();
5687 else
5688 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5689 }
5690 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5691 ZeroInitialization(E);
5692 return true;
5693
5694 case CK_DerivedToBase:
5695 case CK_UncheckedDerivedToBase:
5696 if (!evaluatePointer(E->getSubExpr(), Result))
5697 return false;
5698 if (!Result.Base && Result.Offset.isZero())
5699 return true;
5700
5701 // Now figure out the necessary offset to add to the base LV to get from
5702 // the derived class to the base class.
5703 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5704 castAs<PointerType>()->getPointeeType(),
5705 Result);
5706
5707 case CK_BaseToDerived:
5708 if (!Visit(E->getSubExpr()))
5709 return false;
5710 if (!Result.Base && Result.Offset.isZero())
5711 return true;
5712 return HandleBaseToDerivedCast(Info, E, Result);
5713
5714 case CK_NullToPointer:
5715 VisitIgnoredValue(E->getSubExpr());
5716 return ZeroInitialization(E);
5717
5718 case CK_IntegralToPointer: {
5719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5720
5721 APValue Value;
5722 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5723 break;
5724
5725 if (Value.isInt()) {
5726 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5727 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5728 Result.Base = (Expr*)nullptr;
5729 Result.InvalidBase = false;
5730 Result.Offset = CharUnits::fromQuantity(N);
5731 Result.CallIndex = 0;
5732 Result.Designator.setInvalid();
5733 Result.IsNullPtr = false;
5734 return true;
5735 } else {
5736 // Cast is of an lvalue, no need to change value.
5737 Result.setFrom(Info.Ctx, Value);
5738 return true;
5739 }
5740 }
5741
5742 case CK_ArrayToPointerDecay: {
5743 if (SubExpr->isGLValue()) {
5744 if (!evaluateLValue(SubExpr, Result))
5745 return false;
5746 } else {
5747 Result.set(SubExpr, Info.CurrentCall->Index);
5748 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5749 Info, Result, SubExpr))
5750 return false;
5751 }
5752 // The result is a pointer to the first element of the array.
5753 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5754 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5755 Result.addArray(Info, E, CAT);
5756 else
5757 Result.addUnsizedArray(Info, E, AT->getElementType());
5758 return true;
5759 }
5760
5761 case CK_FunctionToPointerDecay:
5762 return evaluateLValue(SubExpr, Result);
5763
5764 case CK_LValueToRValue: {
5765 LValue LVal;
5766 if (!evaluateLValue(E->getSubExpr(), LVal))
5767 return false;
5768
5769 APValue RVal;
5770 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5771 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5772 LVal, RVal))
5773 return InvalidBaseOK &&
5774 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5775 return Success(RVal, E);
5776 }
5777 }
5778
5779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5780}
5781
5782static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5783 // C++ [expr.alignof]p3:
5784 // When alignof is applied to a reference type, the result is the
5785 // alignment of the referenced type.
5786 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5787 T = Ref->getPointeeType();
5788
5789 // __alignof is defined to return the preferred alignment.
5790 if (T.getQualifiers().hasUnaligned())
5791 return CharUnits::One();
5792 return Info.Ctx.toCharUnitsFromBits(
5793 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5794}
5795
5796static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5797 E = E->IgnoreParens();
5798
5799 // The kinds of expressions that we have special-case logic here for
5800 // should be kept up to date with the special checks for those
5801 // expressions in Sema.
5802
5803 // alignof decl is always accepted, even if it doesn't make sense: we default
5804 // to 1 in those cases.
5805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5806 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5807 /*RefAsPointee*/true);
5808
5809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5810 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5811 /*RefAsPointee*/true);
5812
5813 return GetAlignOfType(Info, E->getType());
5814}
5815
5816// To be clear: this happily visits unsupported builtins. Better name welcomed.
5817bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5818 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5819 return true;
5820
5821 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5822 return false;
5823
5824 Result.setInvalid(E);
5825 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5826 Result.addUnsizedArray(Info, E, PointeeTy);
5827 return true;
5828}
5829
5830bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5831 if (IsStringLiteralCall(E))
5832 return Success(E);
5833
5834 if (unsigned BuiltinOp = E->getBuiltinCallee())
5835 return VisitBuiltinCallExpr(E, BuiltinOp);
5836
5837 return visitNonBuiltinCallExpr(E);
5838}
5839
5840bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5841 unsigned BuiltinOp) {
5842 switch (BuiltinOp) {
5843 case Builtin::BI__builtin_addressof:
5844 return evaluateLValue(E->getArg(0), Result);
5845 case Builtin::BI__builtin_assume_aligned: {
5846 // We need to be very careful here because: if the pointer does not have the
5847 // asserted alignment, then the behavior is undefined, and undefined
5848 // behavior is non-constant.
5849 if (!evaluatePointer(E->getArg(0), Result))
5850 return false;
5851
5852 LValue OffsetResult(Result);
5853 APSInt Alignment;
5854 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5855 return false;
5856 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5857
5858 if (E->getNumArgs() > 2) {
5859 APSInt Offset;
5860 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5861 return false;
5862
5863 int64_t AdditionalOffset = -Offset.getZExtValue();
5864 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5865 }
5866
5867 // If there is a base object, then it must have the correct alignment.
5868 if (OffsetResult.Base) {
5869 CharUnits BaseAlignment;
5870 if (const ValueDecl *VD =
5871 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5872 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5873 } else {
5874 BaseAlignment =
5875 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5876 }
5877
5878 if (BaseAlignment < Align) {
5879 Result.Designator.setInvalid();
5880 // FIXME: Add support to Diagnostic for long / long long.
5881 CCEDiag(E->getArg(0),
5882 diag::note_constexpr_baa_insufficient_alignment) << 0
5883 << (unsigned)BaseAlignment.getQuantity()
5884 << (unsigned)Align.getQuantity();
5885 return false;
5886 }
5887 }
5888
5889 // The offset must also have the correct alignment.
5890 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5891 Result.Designator.setInvalid();
5892
5893 (OffsetResult.Base
5894 ? CCEDiag(E->getArg(0),
5895 diag::note_constexpr_baa_insufficient_alignment) << 1
5896 : CCEDiag(E->getArg(0),
5897 diag::note_constexpr_baa_value_insufficient_alignment))
5898 << (int)OffsetResult.Offset.getQuantity()
5899 << (unsigned)Align.getQuantity();
5900 return false;
5901 }
5902
5903 return true;
5904 }
5905
5906 case Builtin::BIstrchr:
5907 case Builtin::BIwcschr:
5908 case Builtin::BImemchr:
5909 case Builtin::BIwmemchr:
5910 if (Info.getLangOpts().CPlusPlus11)
5911 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5912 << /*isConstexpr*/0 << /*isConstructor*/0
5913 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5914 else
5915 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5916 // Fall through.
5917 case Builtin::BI__builtin_strchr:
5918 case Builtin::BI__builtin_wcschr:
5919 case Builtin::BI__builtin_memchr:
5920 case Builtin::BI__builtin_char_memchr:
5921 case Builtin::BI__builtin_wmemchr: {
5922 if (!Visit(E->getArg(0)))
5923 return false;
5924 APSInt Desired;
5925 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5926 return false;
5927 uint64_t MaxLength = uint64_t(-1);
5928 if (BuiltinOp != Builtin::BIstrchr &&
5929 BuiltinOp != Builtin::BIwcschr &&
5930 BuiltinOp != Builtin::BI__builtin_strchr &&
5931 BuiltinOp != Builtin::BI__builtin_wcschr) {
5932 APSInt N;
5933 if (!EvaluateInteger(E->getArg(2), N, Info))
5934 return false;
5935 MaxLength = N.getExtValue();
5936 }
5937
5938 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5939
5940 // Figure out what value we're actually looking for (after converting to
5941 // the corresponding unsigned type if necessary).
5942 uint64_t DesiredVal;
5943 bool StopAtNull = false;
5944 switch (BuiltinOp) {
5945 case Builtin::BIstrchr:
5946 case Builtin::BI__builtin_strchr:
5947 // strchr compares directly to the passed integer, and therefore
5948 // always fails if given an int that is not a char.
5949 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5950 E->getArg(1)->getType(),
5951 Desired),
5952 Desired))
5953 return ZeroInitialization(E);
5954 StopAtNull = true;
5955 // Fall through.
5956 case Builtin::BImemchr:
5957 case Builtin::BI__builtin_memchr:
5958 case Builtin::BI__builtin_char_memchr:
5959 // memchr compares by converting both sides to unsigned char. That's also
5960 // correct for strchr if we get this far (to cope with plain char being
5961 // unsigned in the strchr case).
5962 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5963 break;
5964
5965 case Builtin::BIwcschr:
5966 case Builtin::BI__builtin_wcschr:
5967 StopAtNull = true;
5968 // Fall through.
5969 case Builtin::BIwmemchr:
5970 case Builtin::BI__builtin_wmemchr:
5971 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5972 DesiredVal = Desired.getZExtValue();
5973 break;
5974 }
5975
5976 for (; MaxLength; --MaxLength) {
5977 APValue Char;
5978 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5979 !Char.isInt())
5980 return false;
5981 if (Char.getInt().getZExtValue() == DesiredVal)
5982 return true;
5983 if (StopAtNull && !Char.getInt())
5984 break;
5985 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5986 return false;
5987 }
5988 // Not found: return nullptr.
5989 return ZeroInitialization(E);
5990 }
5991
5992 default:
5993 return visitNonBuiltinCallExpr(E);
5994 }
5995}
5996
5997//===----------------------------------------------------------------------===//
5998// Member Pointer Evaluation
5999//===----------------------------------------------------------------------===//
6000
6001namespace {
6002class MemberPointerExprEvaluator
6003 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6004 MemberPtr &Result;
6005
6006 bool Success(const ValueDecl *D) {
6007 Result = MemberPtr(D);
6008 return true;
6009 }
6010public:
6011
6012 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6013 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6014
6015 bool Success(const APValue &V, const Expr *E) {
6016 Result.setFrom(V);
6017 return true;
6018 }
6019 bool ZeroInitialization(const Expr *E) {
6020 return Success((const ValueDecl*)nullptr);
6021 }
6022
6023 bool VisitCastExpr(const CastExpr *E);
6024 bool VisitUnaryAddrOf(const UnaryOperator *E);
6025};
6026} // end anonymous namespace
6027
6028static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6029 EvalInfo &Info) {
6030 assert(E->isRValue() && E->getType()->isMemberPointerType())(static_cast <bool> (E->isRValue() && E->
getType()->isMemberPointerType()) ? void (0) : __assert_fail
("E->isRValue() && E->getType()->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6030, __extension__ __PRETTY_FUNCTION__))
;
6031 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6032}
6033
6034bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6035 switch (E->getCastKind()) {
6036 default:
6037 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6038
6039 case CK_NullToMemberPointer:
6040 VisitIgnoredValue(E->getSubExpr());
6041 return ZeroInitialization(E);
6042
6043 case CK_BaseToDerivedMemberPointer: {
6044 if (!Visit(E->getSubExpr()))
6045 return false;
6046 if (E->path_empty())
6047 return true;
6048 // Base-to-derived member pointer casts store the path in derived-to-base
6049 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6050 // the wrong end of the derived->base arc, so stagger the path by one class.
6051 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6052 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6053 PathI != PathE; ++PathI) {
6054 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() &&
"memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6054, __extension__ __PRETTY_FUNCTION__))
;
6055 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6056 if (!Result.castToDerived(Derived))
6057 return Error(E);
6058 }
6059 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6060 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6061 return Error(E);
6062 return true;
6063 }
6064
6065 case CK_DerivedToBaseMemberPointer:
6066 if (!Visit(E->getSubExpr()))
6067 return false;
6068 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6069 PathE = E->path_end(); PathI != PathE; ++PathI) {
6070 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() &&
"memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6070, __extension__ __PRETTY_FUNCTION__))
;
6071 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6072 if (!Result.castToBase(Base))
6073 return Error(E);
6074 }
6075 return true;
6076 }
6077}
6078
6079bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6080 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6081 // member can be formed.
6082 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6083}
6084
6085//===----------------------------------------------------------------------===//
6086// Record Evaluation
6087//===----------------------------------------------------------------------===//
6088
6089namespace {
6090 class RecordExprEvaluator
6091 : public ExprEvaluatorBase<RecordExprEvaluator> {
6092 const LValue &This;
6093 APValue &Result;
6094 public:
6095
6096 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6097 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6098
6099 bool Success(const APValue &V, const Expr *E) {
6100 Result = V;
6101 return true;
6102 }
6103 bool ZeroInitialization(const Expr *E) {
6104 return ZeroInitialization(E, E->getType());
6105 }
6106 bool ZeroInitialization(const Expr *E, QualType T);
6107
6108 bool VisitCallExpr(const CallExpr *E) {
6109 return handleCallExpr(E, Result, &This);
6110 }
6111 bool VisitCastExpr(const CastExpr *E);
6112 bool VisitInitListExpr(const InitListExpr *E);
6113 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6114 return VisitCXXConstructExpr(E, E->getType());
6115 }
6116 bool VisitLambdaExpr(const LambdaExpr *E);
6117 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6118 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6119 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6120 };
6121}
6122
6123/// Perform zero-initialization on an object of non-union class type.
6124/// C++11 [dcl.init]p5:
6125/// To zero-initialize an object or reference of type T means:
6126/// [...]
6127/// -- if T is a (possibly cv-qualified) non-union class type,
6128/// each non-static data member and each base-class subobject is
6129/// zero-initialized
6130static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6131 const RecordDecl *RD,
6132 const LValue &This, APValue &Result) {
6133 assert(!RD->isUnion() && "Expected non-union class type")(static_cast <bool> (!RD->isUnion() && "Expected non-union class type"
) ? void (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6133, __extension__ __PRETTY_FUNCTION__))
;
6134 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6135 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6136 std::distance(RD->field_begin(), RD->field_end()));
6137
6138 if (RD->isInvalidDecl()) return false;
6139 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6140
6141 if (CD) {
6142 unsigned Index = 0;
6143 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6144 End = CD->bases_end(); I != End; ++I, ++Index) {
6145 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6146 LValue Subobject = This;
6147 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6148 return false;
6149 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6150 Result.getStructBase(Index)))
6151 return false;
6152 }
6153 }
6154
6155 for (const auto *I : RD->fields()) {
6156 // -- if T is a reference type, no initialization is performed.
6157 if (I->getType()->isReferenceType())
6158 continue;
6159
6160 LValue Subobject = This;
6161 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6162 return false;
6163
6164 ImplicitValueInitExpr VIE(I->getType());
6165 if (!EvaluateInPlace(
6166 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6167 return false;
6168 }
6169
6170 return true;
6171}
6172
6173bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6174 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6175 if (RD->isInvalidDecl()) return false;
6176 if (RD->isUnion()) {
6177 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6178 // object's first non-static named data member is zero-initialized
6179 RecordDecl::field_iterator I = RD->field_begin();
6180 if (I == RD->field_end()) {
6181 Result = APValue((const FieldDecl*)nullptr);
6182 return true;
6183 }
6184
6185 LValue Subobject = This;
6186 if (!HandleLValueMember(Info, E, Subobject, *I))
6187 return false;
6188 Result = APValue(*I);
6189 ImplicitValueInitExpr VIE(I->getType());
6190 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6191 }
6192
6193 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6194 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6195 return false;
6196 }
6197
6198 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6199}
6200
6201bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6202 switch (E->getCastKind()) {
6203 default:
6204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6205
6206 case CK_ConstructorConversion:
6207 return Visit(E->getSubExpr());
6208
6209 case CK_DerivedToBase:
6210 case CK_UncheckedDerivedToBase: {
6211 APValue DerivedObject;
6212 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6213 return false;
6214 if (!DerivedObject.isStruct())
6215 return Error(E->getSubExpr());
6216
6217 // Derived-to-base rvalue conversion: just slice off the derived part.
6218 APValue *Value = &DerivedObject;
6219 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6220 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6221 PathE = E->path_end(); PathI != PathE; ++PathI) {
6222 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")(static_cast <bool> (!(*PathI)->isVirtual() &&
"record rvalue with virtual base") ? void (0) : __assert_fail
("!(*PathI)->isVirtual() && \"record rvalue with virtual base\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6222, __extension__ __PRETTY_FUNCTION__))
;
6223 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6224 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6225 RD = Base;
6226 }
6227 Result = *Value;
6228 return true;
6229 }
6230 }
6231}
6232
6233bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6234 if (E->isTransparent())
6235 return Visit(E->getInit(0));
6236
6237 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6238 if (RD->isInvalidDecl()) return false;
6239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6240
6241 if (RD->isUnion()) {
6242 const FieldDecl *Field = E->getInitializedFieldInUnion();
6243 Result = APValue(Field);
6244 if (!Field)
6245 return true;
6246
6247 // If the initializer list for a union does not contain any elements, the
6248 // first element of the union is value-initialized.
6249 // FIXME: The element should be initialized from an initializer list.
6250 // Is this difference ever observable for initializer lists which
6251 // we don't build?
6252 ImplicitValueInitExpr VIE(Field->getType());
6253 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6254
6255 LValue Subobject = This;
6256 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6257 return false;
6258
6259 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6260 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6261 isa<CXXDefaultInitExpr>(InitExpr));
6262
6263 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6264 }
6265
6266 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6267 if (Result.isUninit())
6268 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6269 std::distance(RD->field_begin(), RD->field_end()));
6270 unsigned ElementNo = 0;
6271 bool Success = true;
6272
6273 // Initialize base classes.
6274 if (CXXRD) {
6275 for (const auto &Base : CXXRD->bases()) {
6276 assert(ElementNo < E->getNumInits() && "missing init for base class")(static_cast <bool> (ElementNo < E->getNumInits()
&& "missing init for base class") ? void (0) : __assert_fail
("ElementNo < E->getNumInits() && \"missing init for base class\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6276, __extension__ __PRETTY_FUNCTION__))
;
6277 const Expr *Init = E->getInit(ElementNo);
6278
6279 LValue Subobject = This;
6280 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6281 return false;
6282
6283 APValue &FieldVal = Result.getStructBase(ElementNo);
6284 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6285 if (!Info.noteFailure())
6286 return false;
6287 Success = false;
6288 }
6289 ++ElementNo;
6290 }
6291 }
6292
6293 // Initialize members.
6294 for (const auto *Field : RD->fields()) {
6295 // Anonymous bit-fields are not considered members of the class for
6296 // purposes of aggregate initialization.
6297 if (Field->isUnnamedBitfield())
6298 continue;
6299
6300 LValue Subobject = This;
6301
6302 bool HaveInit = ElementNo < E->getNumInits();
6303
6304 // FIXME: Diagnostics here should point to the end of the initializer
6305 // list, not the start.
6306 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6307 Subobject, Field, &Layout))
6308 return false;
6309
6310 // Perform an implicit value-initialization for members beyond the end of
6311 // the initializer list.
6312 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6313 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6314
6315 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6316 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6317 isa<CXXDefaultInitExpr>(Init));
6318
6319 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6320 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6321 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6322 FieldVal, Field))) {
6323 if (!Info.noteFailure())
6324 return false;
6325 Success = false;
6326 }
6327 }
6328
6329 return Success;
6330}
6331
6332bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6333 QualType T) {
6334 // Note that E's type is not necessarily the type of our class here; we might
6335 // be initializing an array element instead.
6336 const CXXConstructorDecl *FD = E->getConstructor();
6337 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6338
6339 bool ZeroInit = E->requiresZeroInitialization();
6340 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6341 // If we've already performed zero-initialization, we're already done.
6342 if (!Result.isUninit())
6343 return true;
6344
6345 // We can get here in two different ways:
6346 // 1) We're performing value-initialization, and should zero-initialize
6347 // the object, or
6348 // 2) We're performing default-initialization of an object with a trivial
6349 // constexpr default constructor, in which case we should start the
6350 // lifetimes of all the base subobjects (there can be no data member
6351 // subobjects in this case) per [basic.life]p1.
6352 // Either way, ZeroInitialization is appropriate.
6353 return ZeroInitialization(E, T);
6354 }
6355
6356 const FunctionDecl *Definition = nullptr;
6357 auto Body = FD->getBody(Definition);
6358
6359 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6360 return false;
6361
6362 // Avoid materializing a temporary for an elidable copy/move constructor.
6363 if (E->isElidable() && !ZeroInit)
6364 if (const MaterializeTemporaryExpr *ME
6365 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6366 return Visit(ME->GetTemporaryExpr());
6367
6368 if (ZeroInit && !ZeroInitialization(E, T))
6369 return false;
6370
6371 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6372 return HandleConstructorCall(E, This, Args,
6373 cast<CXXConstructorDecl>(Definition), Info,
6374 Result);
6375}
6376
6377bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6378 const CXXInheritedCtorInitExpr *E) {
6379 if (!Info.CurrentCall) {
6380 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6380, __extension__ __PRETTY_FUNCTION__))
;
6381 return false;
6382 }
6383
6384 const CXXConstructorDecl *FD = E->getConstructor();
6385 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6386 return false;
6387
6388 const FunctionDecl *Definition = nullptr;
6389 auto Body = FD->getBody(Definition);
6390
6391 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6392 return false;
6393
6394 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6395 cast<CXXConstructorDecl>(Definition), Info,
6396 Result);
6397}
6398
6399bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6400 const CXXStdInitializerListExpr *E) {
6401 const ConstantArrayType *ArrayType =
6402 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6403
6404 LValue Array;
6405 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6406 return false;
6407
6408 // Get a pointer to the first element of the array.
6409 Array.addArray(Info, E, ArrayType);
6410
6411 // FIXME: Perform the checks on the field types in SemaInit.
6412 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6413 RecordDecl::field_iterator Field = Record->field_begin();
6414 if (Field == Record->field_end())
6415 return Error(E);
6416
6417 // Start pointer.
6418 if (!Field->getType()->isPointerType() ||
6419 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6420 ArrayType->getElementType()))
6421 return Error(E);
6422
6423 // FIXME: What if the initializer_list type has base classes, etc?
6424 Result = APValue(APValue::UninitStruct(), 0, 2);
6425 Array.moveInto(Result.getStructField(0));
6426
6427 if (++Field == Record->field_end())
6428 return Error(E);
6429
6430 if (Field->getType()->isPointerType() &&
6431 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6432 ArrayType->getElementType())) {
6433 // End pointer.
6434 if (!HandleLValueArrayAdjustment(Info, E, Array,
6435 ArrayType->getElementType(),
6436 ArrayType->getSize().getZExtValue()))
6437 return false;
6438 Array.moveInto(Result.getStructField(1));
6439 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6440 // Length.
6441 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6442 else
6443 return Error(E);
6444
6445 if (++Field != Record->field_end())
6446 return Error(E);
6447
6448 return true;
6449}
6450
6451bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6452 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6453 if (ClosureClass->isInvalidDecl()) return false;
6454
6455 if (Info.checkingPotentialConstantExpression()) return true;
6456
6457 const size_t NumFields =
6458 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6459
6460 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
6461 E->capture_init_end()) &&(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
6462 "The number of lambda capture initializers should equal the number of "(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
6463 "fields within the closure type")(static_cast <bool> (NumFields == (size_t)std::distance
(E->capture_init_begin(), E->capture_init_end()) &&
"The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? void (0) : __assert_fail
("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
;
6464
6465 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6466 // Iterate through all the lambda's closure object's fields and initialize
6467 // them.
6468 auto *CaptureInitIt = E->capture_init_begin();
6469 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6470 bool Success = true;
6471 for (const auto *Field : ClosureClass->fields()) {
6472 assert(CaptureInitIt != E->capture_init_end())(static_cast <bool> (CaptureInitIt != E->capture_init_end
()) ? void (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6472, __extension__ __PRETTY_FUNCTION__))
;
6473 // Get the initializer for this field
6474 Expr *const CurFieldInit = *CaptureInitIt++;
6475
6476 // If there is no initializer, either this is a VLA or an error has
6477 // occurred.
6478 if (!CurFieldInit)
6479 return Error(E);
6480
6481 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6482 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6483 if (!Info.keepEvaluatingAfterFailure())
6484 return false;
6485 Success = false;
6486 }
6487 ++CaptureIt;
6488 }
6489 return Success;
6490}
6491
6492static bool EvaluateRecord(const Expr *E, const LValue &This,
6493 APValue &Result, EvalInfo &Info) {
6494 assert(E->isRValue() && E->getType()->isRecordType() &&(static_cast <bool> (E->isRValue() && E->
getType()->isRecordType() && "can't evaluate expression as a record rvalue"
) ? void (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
6495 "can't evaluate expression as a record rvalue")(static_cast <bool> (E->isRValue() && E->
getType()->isRecordType() && "can't evaluate expression as a record rvalue"
) ? void (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
;
6496 return RecordExprEvaluator(Info, This, Result).Visit(E);
6497}
6498
6499//===----------------------------------------------------------------------===//
6500// Temporary Evaluation
6501//
6502// Temporaries are represented in the AST as rvalues, but generally behave like
6503// lvalues. The full-object of which the temporary is a subobject is implicitly
6504// materialized so that a reference can bind to it.
6505//===----------------------------------------------------------------------===//
6506namespace {
6507class TemporaryExprEvaluator
6508 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6509public:
6510 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6511 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6512
6513 /// Visit an expression which constructs the value of this temporary.
6514 bool VisitConstructExpr(const Expr *E) {
6515 Result.set(E, Info.CurrentCall->Index);
6516 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6517 Info, Result, E);
6518 }
6519
6520 bool VisitCastExpr(const CastExpr *E) {
6521 switch (E->getCastKind()) {
6522 default:
6523 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6524
6525 case CK_ConstructorConversion:
6526 return VisitConstructExpr(E->getSubExpr());
6527 }
6528 }
6529 bool VisitInitListExpr(const InitListExpr *E) {
6530 return VisitConstructExpr(E);
6531 }
6532 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6533 return VisitConstructExpr(E);
6534 }
6535 bool VisitCallExpr(const CallExpr *E) {
6536 return VisitConstructExpr(E);
6537 }
6538 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6539 return VisitConstructExpr(E);
6540 }
6541 bool VisitLambdaExpr(const LambdaExpr *E) {
6542 return VisitConstructExpr(E);
6543 }
6544};
6545} // end anonymous namespace
6546
6547/// Evaluate an expression of record type as a temporary.
6548static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6549 assert(E->isRValue() && E->getType()->isRecordType())(static_cast <bool> (E->isRValue() && E->
getType()->isRecordType()) ? void (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6549, __extension__ __PRETTY_FUNCTION__))
;
6550 return TemporaryExprEvaluator(Info, Result).Visit(E);
6551}
6552
6553//===----------------------------------------------------------------------===//
6554// Vector Evaluation
6555//===----------------------------------------------------------------------===//
6556
6557namespace {
6558 class VectorExprEvaluator
6559 : public ExprEvaluatorBase<VectorExprEvaluator> {
6560 APValue &Result;
6561 public:
6562
6563 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6564 : ExprEvaluatorBaseTy(info), Result(Result) {}
6565
6566 bool Success(ArrayRef<APValue> V, const Expr *E) {
6567 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())(static_cast <bool> (V.size() == E->getType()->castAs
<VectorType>()->getNumElements()) ? void (0) : __assert_fail
("V.size() == E->getType()->castAs<VectorType>()->getNumElements()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6567, __extension__ __PRETTY_FUNCTION__))
;
6568 // FIXME: remove this APValue copy.
6569 Result = APValue(V.data(), V.size());
6570 return true;
6571 }
6572 bool Success(const APValue &V, const Expr *E) {
6573 assert(V.isVector())(static_cast <bool> (V.isVector()) ? void (0) : __assert_fail
("V.isVector()", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6573, __extension__ __PRETTY_FUNCTION__))
;
6574 Result = V;
6575 return true;
6576 }
6577 bool ZeroInitialization(const Expr *E);
6578
6579 bool VisitUnaryReal(const UnaryOperator *E)
6580 { return Visit(E->getSubExpr()); }
6581 bool VisitCastExpr(const CastExpr* E);
6582 bool VisitInitListExpr(const InitListExpr *E);
6583 bool VisitUnaryImag(const UnaryOperator *E);
6584 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6585 // binary comparisons, binary and/or/xor,
6586 // shufflevector, ExtVectorElementExpr
6587 };
6588} // end anonymous namespace
6589
6590static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6591 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue")(static_cast <bool> (E->isRValue() && E->
getType()->isVectorType() &&"not a vector rvalue")
? void (0) : __assert_fail ("E->isRValue() && E->getType()->isVectorType() &&\"not a vector rvalue\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6591, __extension__ __PRETTY_FUNCTION__))
;
6592 return VectorExprEvaluator(Info, Result).Visit(E);
6593}
6594
6595bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6596 const VectorType *VTy = E->getType()->castAs<VectorType>();
6597 unsigned NElts = VTy->getNumElements();
6598
6599 const Expr *SE = E->getSubExpr();
6600 QualType SETy = SE->getType();
6601
6602 switch (E->getCastKind()) {
6603 case CK_VectorSplat: {
6604 APValue Val = APValue();
6605 if (SETy->isIntegerType()) {
6606 APSInt IntResult;
6607 if (!EvaluateInteger(SE, IntResult, Info))
6608 return false;
6609 Val = APValue(std::move(IntResult));
6610 } else if (SETy->isRealFloatingType()) {
6611 APFloat FloatResult(0.0);
6612 if (!EvaluateFloat(SE, FloatResult, Info))
6613 return false;
6614 Val = APValue(std::move(FloatResult));
6615 } else {
6616 return Error(E);
6617 }
6618
6619 // Splat and create vector APValue.
6620 SmallVector<APValue, 4> Elts(NElts, Val);
6621 return Success(Elts, E);
6622 }
6623 case CK_BitCast: {
6624 // Evaluate the operand into an APInt we can extract from.
6625 llvm::APInt SValInt;
6626 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6627 return false;
6628 // Extract the elements
6629 QualType EltTy = VTy->getElementType();
6630 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6631 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6632 SmallVector<APValue, 4> Elts;
6633 if (EltTy->isRealFloatingType()) {
6634 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6635 unsigned FloatEltSize = EltSize;
6636 if (&Sem == &APFloat::x87DoubleExtended())
6637 FloatEltSize = 80;
6638 for (unsigned i = 0; i < NElts; i++) {
6639 llvm::APInt Elt;
6640 if (BigEndian)
6641 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6642 else
6643 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6644 Elts.push_back(APValue(APFloat(Sem, Elt)));
6645 }
6646 } else if (EltTy->isIntegerType()) {
6647 for (unsigned i = 0; i < NElts; i++) {
6648 llvm::APInt Elt;
6649 if (BigEndian)
6650 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6651 else
6652 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6653 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6654 }
6655 } else {
6656 return Error(E);
6657 }
6658 return Success(Elts, E);
6659 }
6660 default:
6661 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6662 }
6663}
6664
6665bool
6666VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6667 const VectorType *VT = E->getType()->castAs<VectorType>();
6668 unsigned NumInits = E->getNumInits();
6669 unsigned NumElements = VT->getNumElements();
6670
6671 QualType EltTy = VT->getElementType();
6672 SmallVector<APValue, 4> Elements;
6673
6674 // The number of initializers can be less than the number of
6675 // vector elements. For OpenCL, this can be due to nested vector
6676 // initialization. For GCC compatibility, missing trailing elements
6677 // should be initialized with zeroes.
6678 unsigned CountInits = 0, CountElts = 0;
6679 while (CountElts < NumElements) {
6680 // Handle nested vector initialization.
6681 if (CountInits < NumInits
6682 && E->getInit(CountInits)->getType()->isVectorType()) {
6683 APValue v;
6684 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6685 return Error(E);
6686 unsigned vlen = v.getVectorLength();
6687 for (unsigned j = 0; j < vlen; j++)
6688 Elements.push_back(v.getVectorElt(j));
6689 CountElts += vlen;
6690 } else if (EltTy->isIntegerType()) {
6691 llvm::APSInt sInt(32);
6692 if (CountInits < NumInits) {
6693 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6694 return false;
6695 } else // trailing integer zero.
6696 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6697 Elements.push_back(APValue(sInt));
6698 CountElts++;
6699 } else {
6700 llvm::APFloat f(0.0);
6701 if (CountInits < NumInits) {
6702 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6703 return false;
6704 } else // trailing float zero.
6705 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6706 Elements.push_back(APValue(f));
6707 CountElts++;
6708 }
6709 CountInits++;
6710 }
6711 return Success(Elements, E);
6712}
6713
6714bool
6715VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6716 const VectorType *VT = E->getType()->getAs<VectorType>();
6717 QualType EltTy = VT->getElementType();
6718 APValue ZeroElement;
6719 if (EltTy->isIntegerType())
6720 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6721 else
6722 ZeroElement =
6723 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6724
6725 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6726 return Success(Elements, E);
6727}
6728
6729bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6730 VisitIgnoredValue(E->getSubExpr());
6731 return ZeroInitialization(E);
6732}
6733
6734//===----------------------------------------------------------------------===//
6735// Array Evaluation
6736//===----------------------------------------------------------------------===//
6737
6738namespace {
6739 class ArrayExprEvaluator
6740 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6741 const LValue &This;
6742 APValue &Result;
6743 public:
6744
6745 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6746 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6747
6748 bool Success(const APValue &V, const Expr *E) {
6749 assert((V.isArray() || V.isLValue()) &&(static_cast <bool> ((V.isArray() || V.isLValue()) &&
"expected array or string literal") ? void (0) : __assert_fail
("(V.isArray() || V.isLValue()) && \"expected array or string literal\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6750, __extension__ __PRETTY_FUNCTION__))
6750 "expected array or string literal")(static_cast <bool> ((V.isArray() || V.isLValue()) &&
"expected array or string literal") ? void (0) : __assert_fail
("(V.isArray() || V.isLValue()) && \"expected array or string literal\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6750, __extension__ __PRETTY_FUNCTION__))
;
6751 Result = V;
6752 return true;
6753 }
6754
6755 bool ZeroInitialization(const Expr *E) {
6756 const ConstantArrayType *CAT =
6757 Info.Ctx.getAsConstantArrayType(E->getType());
6758 if (!CAT)
6759 return Error(E);
6760
6761 Result = APValue(APValue::UninitArray(), 0,
6762 CAT->getSize().getZExtValue());
6763 if (!Result.hasArrayFiller()) return true;
6764
6765 // Zero-initialize all elements.
6766 LValue Subobject = This;
6767 Subobject.addArray(Info, E, CAT);
6768 ImplicitValueInitExpr VIE(CAT->getElementType());
6769 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6770 }
6771
6772 bool VisitCallExpr(const CallExpr *E) {
6773 return handleCallExpr(E, Result, &This);
6774 }
6775 bool VisitInitListExpr(const InitListExpr *E);
6776 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6777 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6778 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6779 const LValue &Subobject,
6780 APValue *Value, QualType Type);
6781 };
6782} // end anonymous namespace
6783
6784static bool EvaluateArray(const Expr *E, const LValue &This,
6785 APValue &Result, EvalInfo &Info) {
6786 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue")(static_cast <bool> (E->isRValue() && E->
getType()->isArrayType() && "not an array rvalue")
? void (0) : __assert_fail ("E->isRValue() && E->getType()->isArrayType() && \"not an array rvalue\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6786, __extension__ __PRETTY_FUNCTION__))
;
6787 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6788}
6789
6790bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6791 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6792 if (!CAT)
1
Assuming 'CAT' is non-null
2
Taking false branch
6793 return Error(E);
6794
6795 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6796 // an appropriately-typed string literal enclosed in braces.
6797 if (E->isStringLiteralInit()) {
3
Assuming the condition is false
4
Taking false branch
6798 LValue LV;
6799 if (!EvaluateLValue(E->getInit(0), LV, Info))
6800 return false;
6801 APValue Val;
6802 LV.moveInto(Val);
6803 return Success(Val, E);
6804 }
6805
6806 bool Success = true;
6807
6808 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts
() == 0) && "zero-initialized array shouldn't have any initialized elts"
) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6809, __extension__ __PRETTY_FUNCTION__))
6809 "zero-initialized array shouldn't have any initialized elts")(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts
() == 0) && "zero-initialized array shouldn't have any initialized elts"
) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6809, __extension__ __PRETTY_FUNCTION__))
;
6810 APValue Filler;
6811 if (Result.isArray() && Result.hasArrayFiller())
6812 Filler = Result.getArrayFiller();
6813
6814 unsigned NumEltsToInit = E->getNumInits();
6815 unsigned NumElts = CAT->getSize().getZExtValue();
6816 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5
Assuming the condition is false
6
'?' condition is false
7
'FillerExpr' initialized to a null pointer value
6817
6818 // If the initializer might depend on the array index, run it for each
6819 // array element. For now, just whitelist non-class value-initialization.
6820 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6821 NumEltsToInit = NumElts;
6822
6823 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6824
6825 // If the array was previously zero-initialized, preserve the
6826 // zero-initialized values.
6827 if (!Filler.isUninit()) {
8
Taking false branch
6828 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6829 Result.getArrayInitializedElt(I) = Filler;
6830 if (Result.hasArrayFiller())
6831 Result.getArrayFiller() = Filler;
6832 }
6833
6834 LValue Subobject = This;
6835 Subobject.addArray(Info, E, CAT);
6836 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9
Assuming 'Index' is not equal to 'NumEltsToInit'
10
Loop condition is true. Entering loop body
6837 const Expr *Init =
13
'Init' initialized to a null pointer value
6838 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
11
Assuming the condition is false
12
'?' condition is false
6839 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14
Assuming the condition is false
6840 Info, Subobject, Init) ||
6841 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15
Passing null pointer value via 2nd parameter 'E'
16
Calling 'HandleLValueArrayAdjustment'
6842 CAT->getElementType(), 1)) {
6843 if (!Info.noteFailure())
6844 return false;
6845 Success = false;
6846 }
6847 }
6848
6849 if (!Result.hasArrayFiller())
6850 return Success;
6851
6852 // If we get here, we have a trivial filler, which we can just evaluate
6853 // once and splat over the rest of the array elements.
6854 assert(FillerExpr && "no array filler for incomplete init list")(static_cast <bool> (FillerExpr && "no array filler for incomplete init list"
) ? void (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6854, __extension__ __PRETTY_FUNCTION__))
;
6855 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6856 FillerExpr) && Success;
6857}
6858
6859bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6860 if (E->getCommonExpr() &&
6861 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6862 Info, E->getCommonExpr()->getSourceExpr()))
6863 return false;
6864
6865 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6866
6867 uint64_t Elements = CAT->getSize().getZExtValue();
6868 Result = APValue(APValue::UninitArray(), Elements, Elements);
6869
6870 LValue Subobject = This;
6871 Subobject.addArray(Info, E, CAT);
6872
6873 bool Success = true;
6874 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6875 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6876 Info, Subobject, E->getSubExpr()) ||
6877 !HandleLValueArrayAdjustment(Info, E, Subobject,
6878 CAT->getElementType(), 1)) {
6879 if (!Info.noteFailure())
6880 return false;
6881 Success = false;
6882 }
6883 }
6884
6885 return Success;
6886}
6887
6888bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6889 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6890}
6891
6892bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6893 const LValue &Subobject,
6894 APValue *Value,
6895 QualType Type) {
6896 bool HadZeroInit = !Value->isUninit();
6897
6898 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6899 unsigned N = CAT->getSize().getZExtValue();
6900
6901 // Preserve the array filler if we had prior zero-initialization.
6902 APValue Filler =
6903 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6904 : APValue();
6905
6906 *Value = APValue(APValue::UninitArray(), N, N);
6907
6908 if (HadZeroInit)
6909 for (unsigned I = 0; I != N; ++I)
6910 Value->getArrayInitializedElt(I) = Filler;
6911
6912 // Initialize the elements.
6913 LValue ArrayElt = Subobject;
6914 ArrayElt.addArray(Info, E, CAT);
6915 for (unsigned I = 0; I != N; ++I)
6916 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6917 CAT->getElementType()) ||
6918 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6919 CAT->getElementType(), 1))
6920 return false;
6921
6922 return true;
6923 }
6924
6925 if (!Type->isRecordType())
6926 return Error(E);
6927
6928 return RecordExprEvaluator(Info, Subobject, *Value)
6929 .VisitCXXConstructExpr(E, Type);
6930}
6931
6932//===----------------------------------------------------------------------===//
6933// Integer Evaluation
6934//
6935// As a GNU extension, we support casting pointers to sufficiently-wide integer
6936// types and back in constant folding. Integer values are thus represented
6937// either as an integer-valued APValue, or as an lvalue-valued APValue.
6938//===----------------------------------------------------------------------===//
6939
6940namespace {
6941class IntExprEvaluator
6942 : public ExprEvaluatorBase<IntExprEvaluator> {
6943 APValue &Result;
6944public:
6945 IntExprEvaluator(EvalInfo &info, APValue &result)
6946 : ExprEvaluatorBaseTy(info), Result(result) {}
6947
6948 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6949 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6950, __extension__ __PRETTY_FUNCTION__))
6950 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6950, __extension__ __PRETTY_FUNCTION__))
;
6951 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&(static_cast <bool> (SI.isSigned() == E->getType()->
isSignedIntegerOrEnumerationType() && "Invalid evaluation result."
) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6952, __extension__ __PRETTY_FUNCTION__))
6952 "Invalid evaluation result.")(static_cast <bool> (SI.isSigned() == E->getType()->
isSignedIntegerOrEnumerationType() && "Invalid evaluation result."
) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6952, __extension__ __PRETTY_FUNCTION__))
;
6953 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6954, __extension__ __PRETTY_FUNCTION__))
6954 "Invalid evaluation result.")(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6954, __extension__ __PRETTY_FUNCTION__))
;
6955 Result = APValue(SI);
6956 return true;
6957 }
6958 bool Success(const llvm::APSInt &SI, const Expr *E) {
6959 return Success(SI, E, Result);
6960 }
6961
6962 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6963 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6964, __extension__ __PRETTY_FUNCTION__))
6964 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6964, __extension__ __PRETTY_FUNCTION__))
;
6965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6966, __extension__ __PRETTY_FUNCTION__))
6966 "Invalid evaluation result.")(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth
(E->getType()) && "Invalid evaluation result.") ? void
(0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6966, __extension__ __PRETTY_FUNCTION__))
;
6967 Result = APValue(APSInt(I));
6968 Result.getInt().setIsUnsigned(
6969 E->getType()->isUnsignedIntegerOrEnumerationType());
6970 return true;
6971 }
6972 bool Success(const llvm::APInt &I, const Expr *E) {
6973 return Success(I, E, Result);
6974 }
6975
6976 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6977 assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6978, __extension__ __PRETTY_FUNCTION__))
6978 "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType
() && "Invalid evaluation result.") ? void (0) : __assert_fail
("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 6978, __extension__ __PRETTY_FUNCTION__))
;
6979 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6980 return true;
6981 }
6982 bool Success(uint64_t Value, const Expr *E) {
6983 return Success(Value, E, Result);
6984 }
6985
6986 bool Success(CharUnits Size, const Expr *E) {
6987 return Success(Size.getQuantity(), E);
6988 }
6989
6990 bool Success(const APValue &V, const Expr *E) {
6991 if (V.isLValue() || V.isAddrLabelDiff()) {
6992 Result = V;
6993 return true;
6994 }
6995 return Success(V.getInt(), E);
6996 }
6997
6998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6999
7000 //===--------------------------------------------------------------------===//
7001 // Visitor Methods
7002 //===--------------------------------------------------------------------===//
7003
7004 bool VisitIntegerLiteral(const IntegerLiteral *E) {
7005 return Success(E->getValue(), E);
7006 }
7007 bool VisitCharacterLiteral(const CharacterLiteral *E) {
7008 return Success(E->getValue(), E);
7009 }
7010
7011 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7012 bool VisitDeclRefExpr(const DeclRefExpr *E) {
7013 if (CheckReferencedDecl(E, E->getDecl()))
7014 return true;
7015
7016 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7017 }
7018 bool VisitMemberExpr(const MemberExpr *E) {
7019 if (CheckReferencedDecl(E, E->getMemberDecl())) {
7020 VisitIgnoredBaseExpression(E->getBase());
7021 return true;
7022 }
7023
7024 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7025 }
7026
7027 bool VisitCallExpr(const CallExpr *E);
7028 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7029 bool VisitBinaryOperator(const BinaryOperator *E);
7030 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7031 bool VisitUnaryOperator(const UnaryOperator *E);
7032
7033 bool VisitCastExpr(const CastExpr* E);
7034 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7035
7036 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7037 return Success(E->getValue(), E);
7038 }
7039
7040 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7041 return Success(E->getValue(), E);
7042 }
7043
7044 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7045 if (Info.ArrayInitIndex == uint64_t(-1)) {
7046 // We were asked to evaluate this subexpression independent of the
7047 // enclosing ArrayInitLoopExpr. We can't do that.
7048 Info.FFDiag(E);
7049 return false;
7050 }
7051 return Success(Info.ArrayInitIndex, E);
7052 }
7053
7054 // Note, GNU defines __null as an integer, not a pointer.
7055 bool VisitGNUNullExpr(const GNUNullExpr *E) {
7056 return ZeroInitialization(E);
7057 }
7058
7059 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7060 return Success(E->getValue(), E);
7061 }
7062
7063 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7064 return Success(E->getValue(), E);
7065 }
7066
7067 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7068 return Success(E->getValue(), E);
7069 }
7070
7071 bool VisitUnaryReal(const UnaryOperator *E);
7072 bool VisitUnaryImag(const UnaryOperator *E);
7073
7074 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7075 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7076
7077 // FIXME: Missing: array subscript of vector, member of vector
7078};
7079} // end anonymous namespace
7080
7081/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7082/// produce either the integer value or a pointer.
7083///
7084/// GCC has a heinous extension which folds casts between pointer types and
7085/// pointer-sized integral types. We support this by allowing the evaluation of
7086/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7087/// Some simple arithmetic on such values is supported (they are treated much
7088/// like char*).
7089static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7090 EvalInfo &Info) {
7091 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->isRValue() && E->
getType()->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("E->isRValue() && E->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7091, __extension__ __PRETTY_FUNCTION__))
;
7092 return IntExprEvaluator(Info, Result).Visit(E);
7093}
7094
7095static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7096 APValue Val;
7097 if (!EvaluateIntegerOrLValue(E, Val, Info))
7098 return false;
7099 if (!Val.isInt()) {
7100 // FIXME: It would be better to produce the diagnostic for casting
7101 // a pointer to an integer.
7102 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7103 return false;
7104 }
7105 Result = Val.getInt();
7106 return true;
7107}
7108
7109/// Check whether the given declaration can be directly converted to an integral
7110/// rvalue. If not, no diagnostic is produced; there are other things we can
7111/// try.
7112bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7113 // Enums are integer constant exprs.
7114 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7115 // Check for signedness/width mismatches between E type and ECD value.
7116 bool SameSign = (ECD->getInitVal().isSigned()
7117 == E->getType()->isSignedIntegerOrEnumerationType());
7118 bool SameWidth = (ECD->getInitVal().getBitWidth()
7119 == Info.Ctx.getIntWidth(E->getType()));
7120 if (SameSign && SameWidth)
7121 return Success(ECD->getInitVal(), E);
7122 else {
7123 // Get rid of mismatch (otherwise Success assertions will fail)
7124 // by computing a new value matching the type of E.
7125 llvm::APSInt Val = ECD->getInitVal();
7126 if (!SameSign)
7127 Val.setIsSigned(!ECD->getInitVal().isSigned());
7128 if (!SameWidth)
7129 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7130 return Success(Val, E);
7131 }
7132 }
7133 return false;
7134}
7135
7136/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7137/// as GCC.
7138static int EvaluateBuiltinClassifyType(const CallExpr *E,
7139 const LangOptions &LangOpts) {
7140 // The following enum mimics the values returned by GCC.
7141 // FIXME: Does GCC differ between lvalue and rvalue references here?
7142 enum gcc_type_class {
7143 no_type_class = -1,
7144 void_type_class, integer_type_class, char_type_class,
7145 enumeral_type_class, boolean_type_class,
7146 pointer_type_class, reference_type_class, offset_type_class,
7147 real_type_class, complex_type_class,
7148 function_type_class, method_type_class,
7149 record_type_class, union_type_class,
7150 array_type_class, string_type_class,
7151 lang_type_class
7152 };
7153
7154 // If no argument was supplied, default to "no_type_class". This isn't
7155 // ideal, however it is what gcc does.
7156 if (E->getNumArgs() == 0)
7157 return no_type_class;
7158
7159 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7160 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7161
7162 switch (CanTy->getTypeClass()) {
7163#define TYPE(ID, BASE)
7164#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7165#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7166#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7167#include "clang/AST/TypeNodes.def"
7168 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7168)
;
7169
7170 case Type::Builtin:
7171 switch (BT->getKind()) {
7172#define BUILTIN_TYPE(ID, SINGLETON_ID)
7173#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7174#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7175#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7176#include "clang/AST/BuiltinTypes.def"
7177 case BuiltinType::Void:
7178 return void_type_class;
7179
7180 case BuiltinType::Bool:
7181 return boolean_type_class;
7182
7183 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7184 case BuiltinType::UChar:
7185 case BuiltinType::UShort:
7186 case BuiltinType::UInt:
7187 case BuiltinType::ULong:
7188 case BuiltinType::ULongLong:
7189 case BuiltinType::UInt128:
7190 return integer_type_class;
7191
7192 case BuiltinType::NullPtr:
7193 return pointer_type_class;
7194
7195 case BuiltinType::WChar_U:
7196 case BuiltinType::Char16:
7197 case BuiltinType::Char32:
7198 case BuiltinType::ObjCId:
7199 case BuiltinType::ObjCClass:
7200 case BuiltinType::ObjCSel:
7201#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7202 case BuiltinType::Id:
7203#include "clang/Basic/OpenCLImageTypes.def"
7204 case BuiltinType::OCLSampler:
7205 case BuiltinType::OCLEvent:
7206 case BuiltinType::OCLClkEvent:
7207 case BuiltinType::OCLQueue:
7208 case BuiltinType::OCLReserveID:
7209 case BuiltinType::Dependent:
7210 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7210)
;
7211 };
7212
7213 case Type::Enum:
7214 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7215 break;
7216
7217 case Type::Pointer:
7218 return pointer_type_class;
7219 break;
7220
7221 case Type::MemberPointer:
7222 if (CanTy->isMemberDataPointerType())
7223 return offset_type_class;
7224 else {
7225 // We expect member pointers to be either data or function pointers,
7226 // nothing else.
7227 assert(CanTy->isMemberFunctionPointerType())(static_cast <bool> (CanTy->isMemberFunctionPointerType
()) ? void (0) : __assert_fail ("CanTy->isMemberFunctionPointerType()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7227, __extension__ __PRETTY_FUNCTION__))
;
7228 return method_type_class;
7229 }
7230
7231 case Type::Complex:
7232 return complex_type_class;
7233
7234 case Type::FunctionNoProto:
7235 case Type::FunctionProto:
7236 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7237
7238 case Type::Record:
7239 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7240 switch (RT->getDecl()->getTagKind()) {
7241 case TagTypeKind::TTK_Struct:
7242 case TagTypeKind::TTK_Class:
7243 case TagTypeKind::TTK_Interface:
7244 return record_type_class;
7245
7246 case TagTypeKind::TTK_Enum:
7247 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7248
7249 case TagTypeKind::TTK_Union:
7250 return union_type_class;
7251 }
7252 }
7253 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7253)
;
7254
7255 case Type::ConstantArray:
7256 case Type::VariableArray:
7257 case Type::IncompleteArray:
7258 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7259
7260 case Type::BlockPointer:
7261 case Type::LValueReference:
7262 case Type::RValueReference:
7263 case Type::Vector:
7264 case Type::ExtVector:
7265 case Type::Auto:
7266 case Type::DeducedTemplateSpecialization:
7267 case Type::ObjCObject:
7268 case Type::ObjCInterface:
7269 case Type::ObjCObjectPointer:
7270 case Type::Pipe:
7271 case Type::Atomic:
7272 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7272)
;
7273 }
7274
7275 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7275)
;
7276}
7277
7278/// EvaluateBuiltinConstantPForLValue - Determine the result of
7279/// __builtin_constant_p when applied to the given lvalue.
7280///
7281/// An lvalue is only "constant" if it is a pointer or reference to the first
7282/// character of a string literal.
7283template<typename LValue>
7284static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7285 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7286 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7287}
7288
7289/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7290/// GCC as we can manage.
7291static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7292 QualType ArgType = Arg->getType();
7293
7294 // __builtin_constant_p always has one operand. The rules which gcc follows
7295 // are not precisely documented, but are as follows:
7296 //
7297 // - If the operand is of integral, floating, complex or enumeration type,
7298 // and can be folded to a known value of that type, it returns 1.
7299 // - If the operand and can be folded to a pointer to the first character
7300 // of a string literal (or such a pointer cast to an integral type), it
7301 // returns 1.
7302 //
7303 // Otherwise, it returns 0.
7304 //
7305 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7306 // its support for this does not currently work.
7307 if (ArgType->isIntegralOrEnumerationType()) {
7308 Expr::EvalResult Result;
7309 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7310 return false;
7311
7312 APValue &V = Result.Val;
7313 if (V.getKind() == APValue::Int)
7314 return true;
7315 if (V.getKind() == APValue::LValue)
7316 return EvaluateBuiltinConstantPForLValue(V);
7317 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7318 return Arg->isEvaluatable(Ctx);
7319 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7320 LValue LV;
7321 Expr::EvalStatus Status;
7322 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7323 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7324 : EvaluatePointer(Arg, LV, Info)) &&
7325 !Status.HasSideEffects)
7326 return EvaluateBuiltinConstantPForLValue(LV);
7327 }
7328
7329 // Anything else isn't considered to be sufficiently constant.
7330 return false;
7331}
7332
7333/// Retrieves the "underlying object type" of the given expression,
7334/// as used by __builtin_object_size.
7335static QualType getObjectType(APValue::LValueBase B) {
7336 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7337 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7338 return VD->getType();
7339 } else if (const Expr *E = B.get<const Expr*>()) {
7340 if (isa<CompoundLiteralExpr>(E))
7341 return E->getType();
7342 }
7343
7344 return QualType();
7345}
7346
7347/// A more selective version of E->IgnoreParenCasts for
7348/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7349/// to change the type of E.
7350/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7351///
7352/// Always returns an RValue with a pointer representation.
7353static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7354 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-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7354, __extension__ __PRETTY_FUNCTION__))
;
7355
7356 auto *NoParens = E->IgnoreParens();
7357 auto *Cast = dyn_cast<CastExpr>(NoParens);
7358 if (Cast == nullptr)
7359 return NoParens;
7360
7361 // We only conservatively allow a few kinds of casts, because this code is
7362 // inherently a simple solution that seeks to support the common case.
7363 auto CastKind = Cast->getCastKind();
7364 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7365 CastKind != CK_AddressSpaceConversion)
7366 return NoParens;
7367
7368 auto *SubExpr = Cast->getSubExpr();
7369 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7370 return NoParens;
7371 return ignorePointerCastsAndParens(SubExpr);
7372}
7373
7374/// Checks to see if the given LValue's Designator is at the end of the LValue's
7375/// record layout. e.g.
7376/// struct { struct { int a, b; } fst, snd; } obj;
7377/// obj.fst // no
7378/// obj.snd // yes
7379/// obj.fst.a // no
7380/// obj.fst.b // no
7381/// obj.snd.a // no
7382/// obj.snd.b // yes
7383///
7384/// Please note: this function is specialized for how __builtin_object_size
7385/// views "objects".
7386///
7387/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7388/// correct result, it will always return true.
7389static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7390 assert(!LVal.Designator.Invalid)(static_cast <bool> (!LVal.Designator.Invalid) ? void (
0) : __assert_fail ("!LVal.Designator.Invalid", "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7390, __extension__ __PRETTY_FUNCTION__))
;
7391
7392 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7393 const RecordDecl *Parent = FD->getParent();
7394 Invalid = Parent->isInvalidDecl();
7395 if (Invalid || Parent->isUnion())
7396 return true;
7397 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7398 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7399 };
7400
7401 auto &Base = LVal.getLValueBase();
7402 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7403 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7404 bool Invalid;
7405 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7406 return Invalid;
7407 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7408 for (auto *FD : IFD->chain()) {
7409 bool Invalid;
7410 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7411 return Invalid;
7412 }
7413 }
7414 }
7415
7416 unsigned I = 0;
7417 QualType BaseType = getType(Base);
7418 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7419 // If we don't know the array bound, conservatively assume we're looking at
7420 // the final array element.
7421 ++I;
7422 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7423 }
7424
7425 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7426 const auto &Entry = LVal.Designator.Entries[I];
7427 if (BaseType->isArrayType()) {
7428 // Because __builtin_object_size treats arrays as objects, we can ignore
7429 // the index iff this is the last array in the Designator.
7430 if (I + 1 == E)
7431 return true;
7432 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7433 uint64_t Index = Entry.ArrayIndex;
7434 if (Index + 1 != CAT->getSize())
7435 return false;
7436 BaseType = CAT->getElementType();
7437 } else if (BaseType->isAnyComplexType()) {
7438 const auto *CT = BaseType->castAs<ComplexType>();
7439 uint64_t Index = Entry.ArrayIndex;
7440 if (Index != 1)
7441 return false;
7442 BaseType = CT->getElementType();
7443 } else if (auto *FD = getAsField(Entry)) {
7444 bool Invalid;
7445 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7446 return Invalid;
7447 BaseType = FD->getType();
7448 } else {
7449 assert(getAsBaseClass(Entry) && "Expecting cast to a base class")(static_cast <bool> (getAsBaseClass(Entry) && "Expecting cast to a base class"
) ? void (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/clang/lib/AST/ExprConstant.cpp"
, 7449, __extension__ __PRETTY_FUNCTION__))
;
7450 return false;
7451 }
7452 }
7453 return true;
7454}
7455
7456/// Tests to see if the LValue has a user-specified designator (that isn't
7457/// necessarily valid). Note that this always returns 'true' if the LValue has
7458/// an unsized array as its first designator entry, because there's currently no
7459/// way to tell if the user typed *foo or foo[0].
7460static bool refersToCompleteObject(const LValue &LVal) {
7461 if (LVal.Designator.Invalid)
7462 return false;
7463
7464 if (!LVal.Designator.Entries.empty())
7465 return LVal.Designator.isMostDerivedAnUnsizedArray();
7466
7467 if (!LVal.InvalidBase)
7468 return true;
7469
7470 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7471 // the LValueBase.
7472 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7473 return !E || !isa<MemberExpr>(E);
7474}
7475
7476/// Attempts to detect a user writing into a piece of memory that's impossible
7477/// to figure out the size of by just using types.
7478static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7479 const SubobjectDesignator &Designator = LVal.Designator;
7480 // Notes:
7481 // - Users can only write off of the end when we have an invalid base. Invalid
7482 // bases imply we don't know where the memory came from.
7483 // - We used to be a bit more aggressive here; we'd only be conservative if
7484 // the array at the end was flexible, or if it had 0 or 1 elements. This
7485 // broke some common standard library extensions (PR30346), but was
7486 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7487 // with some sort of whitelist. OTOH, it seems that GCC is always
7488 // conservative with the last element in structs (if it's an array), so our
7489 // current behavior is more compatible than a whitelisting approach would
7490 // be.
7491 return LVal.InvalidBase &&
7492 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7493 Designator.MostDerivedIsArrayElement &&
7494 isDesignatorAtObjectEnd(Ctx, LVal);
7495}
7496
7497/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7498/// Fails if the conversion would cause loss of precision.
7499static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7500 CharUnits &Result) {
7501 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7502 if (Int.ugt(CharUnitsMax))
7503 return false;
7504 Result = CharUnits::fromQuantity(Int.getZExtValue());
7505 return true;
7506}
7507
7508/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7509/// determine how many bytes exist from the beginning of the object to either
7510/// the end of the current subobject, or the end of the object itself, depending
7511/// on what the LValue looks like + the value of Type.
7512///
7513/// If this returns false, the value of Result is undefined.
7514static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7515 unsigned Type, const LValue &LVal,
7516 CharUnits &EndOffset) {
7517 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7518
7519 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7520 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7521 return false;
7522 return HandleSizeof(Info, ExprLoc, Ty, Result);
7523 };
7524
7525 // We want to evaluate the size of the entire object. This is a valid fallback
7526 // for when Type=1 and the designator is invalid, because we're asked for an
7527 // upper-bound.
7528 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7529 // Type=3 wants a lower bound, so we can't fall back to this.
7530 if (Type == 3 && !DetermineForCompleteObject)
7531 return false;
7532
7533 llvm::APInt APEndOffset;
7534 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7535 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7536 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7537
7538 if (LVal.InvalidBase)
7539 return false;
7540
7541 QualType BaseTy = getObjectType(LVal.getLValueBase());
7542 return CheckedHandleSizeof(BaseTy, EndOffset);
7543 }
7544
7545 // We want to evaluate the size of a subobject.
7546 const SubobjectDesignator &Designator = LVal.Designator;
7547
7548 // The following is a moderately common idiom in C:
7549 //
7550 // struct Foo { int a; char c[1]; };
7551 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7552 // strcpy(&F->c[0], Bar);
7553 //
7554 // In order to not break too much legacy code, we need to support it.
7555 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7556 // If we can resolve this to an alloc_size call, we can hand that back,
7557 // because we know for certain how many bytes there are to write to.
7558 llvm::APInt APEndOffset;
7559 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7560 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7561 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7562
7563 // If we cannot determine the size of the initial allocation, then we can't
7564 // given an accurate upper-bound. However, we are still able to give
7565 // conservative lower-bounds for Type=3.
7566 if (Type == 1)
7567 return false;
7568 }
7569
7570 CharUnits BytesPerElem;
7571 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7572 return false;
7573
7574 // According to the GCC documentation, we want the size of the subobject
7575 // denoted by the pointer. But that's not quite right -- what we actually
7576 // want is the size of the immediately-enclosing array, if there is one.
7577 int64_t ElemsRemaining;
7578 if (Designator.MostDerivedIsArrayElement &&
7579 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7580 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7581 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7582 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7583 } else {
7584 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7585 }
7586
7587 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7588 return true;
7589}
7590
7591/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7592/// returns true and stores the result in @p Size.
7593///
7594/// If @p WasError is non-null, this will report whether the failure to evaluate
7595/// is to be treated as an Error in IntExprEvaluator.
7596static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7597 EvalInfo &Info, uint64_t &Size) {
7598 // Determine the denoted object.
7599 LValue LVal;
7600 {
7601 // The operand of __builtin_object_size is never evaluated for side-effects.
7602 // If there are any, but we can determine the pointed-to object anyway, then
7603 // ignore the side-effects.
7604 SpeculativeEvaluationRAII SpeculativeEval(Info);
7605 FoldOffsetRAII Fold(Info);
7606
7607 if (E->isGLValue()) {
7608 // It's possible for us to be given GLValues if we're called via
7609 // Expr::tryEvaluateObjectSize.
7610 APValue RVal;
7611 if (!EvaluateAsRValue(Info, E, RVal))
7612 return false;
7613 LVal.setFrom(Info.Ctx, RVal);
7614 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7615 /*InvalidBaseOK=*/true))
7616 return false;
7617 }
7618
7619 // If we point to before the start of the object, there are no accessible
7620 // bytes.
7621 if (LVal.getLValueOffset().isNegative()) {
7622 Size = 0;
7623 return true;
7624 }
7625
7626 CharUnits EndOffset;
7627 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7628 return false;
7629
7630 // If we've fa