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